Adding Security To Chat Client - c#

So this is my basic chat program which allows user to add its own IP and receive an IP, plus custom ports to communicate.
In the windows forms design I have:
Textbox --- textLocalIp
Textbox --- textLocalPort
Textbox --- textFriendIp
Textbox --- textFriendPort
Textbox --- textMessage
Listbox --- listMessage
Button --- Start
Button --- Send
So this is a very basic client but what I want help with is making it secure/more secure because security right now is not good.
Maybe like a tunnel with different IP's so that you don't have to know the receivers IP, just a IP they provide which then sends it to them or whatever?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Client
{
public partial class Form1 : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Form1()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textLocalIp.Text = GetLocalIP();
textFriendIp.Text = GetLocalIP();
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] recievedData = new byte[1464];
recievedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(recievedData);
listMessage.Items.Add("Sender: "+receivedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textMessage.Text);
sck.Send(msg);
listMessage.Items.Add("Local:" + textMessage.Text);
textMessage.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void start_Click(object sender, EventArgs e)
{
try
{
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(textFriendIp.Text), Convert.ToInt32(textFriendPort.Text));
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
start.Text = "Connected";
start.Enabled = false;
send.Enabled = true;
textMessage.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

It is more difficult to implement socket communication security using channels. So I suggest you encrypt the IP and transmission content.
For IP encryption, you can set the Passwordchar attribute of the TextBox to *.
For transmission content, you can encrypt it with an encryption algorithm.
The following code implements the communication between a server and multiple clients, and you can perform encryption on this basis.
Server:
namespace Server
{
class Program
{
private static byte[] result = new byte[1024];
private static int myProt = 8885;
static Socket serverSocket;
static void Main(string[] args)
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, myProt));
serverSocket.Listen(10); //Set up to 10 queued connection requests
Console.WriteLine("Start listening {0} successfully", serverSocket.LocalEndPoint.ToString());
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
/// <summary>
/// Listen for Client connections
/// </summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
/// <summary>
/// receive data
/// </summary>
/// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("Receive client {0} message {1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
Client:
namespace Client
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8885));
Console.WriteLine("Successfully connected to the server");
}
catch
{
Console.WriteLine("Failed to connect to the server, please press Enter to exit!");
return;
}
//Receive data through clientSocket
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("Server:{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
//Send data through clientSocket
for (int i = 0; i <3; i++)
{
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hellp" + DateTime.Now;
clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("Client:{0}" + sendMessage);
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
Console.WriteLine("After sending, press Enter to exit");
Console.ReadLine();
}
}
}

Related

C# Asynchronous Chat Server

I'm trying to build an Asynchronous Chat Server and this is what I got so far:
Server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
byte[] bytes = new Byte[1024];
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",content.Length, content);
Send(handler, content);
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
Client
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 256;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient
{
private const int port = 11000;
private static ManualResetEvent connectDone =new ManualResetEvent(false);
private static ManualResetEvent sendDone =new ManualResetEvent(false);
private static ManualResetEvent receiveDone =new ManualResetEvent(false);
private static String response = String.Empty;
static String username = "";
static int a = 1;
private static void StartClient()
{
try
{
Console.WriteLine("Username: ");
username = Console.ReadLine();
while (a == 1)
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
Console.WriteLine("Receiver: ");
String receiver = Console.ReadLine();
Console.WriteLine("Message: ");
String message = Console.ReadLine();
String Message = username + "[" + receiver + "[" + message + "<EOF>";
Send(client, Message);
sendDone.WaitOne();
Receive(client);
receiveDone.WaitOne();
Console.WriteLine("Response received : {0}", response);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(Socket client, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
client.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartClient();
return 0;
}
}
I'm able to send messages to the server and get back an answer, but the connection is cut every time and I have to reconnect it and like this I wouldn't be able to get messages after I send one. I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.
Furthermore I'm looking for a way to send messages from one client to another one and to send a message to all clients, who are connected to the server.
Another Question I have, how can I set up multiple ports and let the server listen to all ports? I wanted to open one port for the login and one port for the messages.
I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.
Closing the connection could be done by adding a disconnect call after the loop: client.Disconnect(false). After some exit condition you simply quit the loop.
It would be preferable to create the client in a using statement though, this way it will be disposed automatically.
but the connection is cut every time
because your explicitly close it in SendCallback
Socket handler = (Socket) ar.AsyncState;
handler.Shutdown(SocketShutdown.Both);
handler.Close();
You may call handler.BeginReceive instead

Visual Studio 2017 C# Sockets UDP

Im having a hard time figuring this out.
I'm trying to make a chat where there's one server and multiple clients but I can't seem to get it to work.
Im using Visual Studio 2017 and it's a Windows Forms App .NET Framework project. Now, it works but only 2 clients can connect to each other. If I try to connect two users to one, one gets blocked out of the conversation and can't recive messages from the server.
To the question: Is it possible to make a server that many clients can connect to and the server can send messages to all connected clients?
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace ChatProgram
{
public partial class Window : Form
{
Socket sck;
EndPoint epLocal, epRemote;
public Window()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //Starts New Socket In InternNetwork Dgram Protocoltype UDP
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPMe.Text = GetLocalIP(); //Sets My IP Bar To My Local IP
}
private string GetLocalIP() //Gets Local IP From Computer
{
Send.Enabled = false;
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] recivedData = new byte[1464];
recivedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string recivedMessage = eEncoding.GetString(recivedData);
MessageBox.Items.Add("" + recivedMessage); //Paste Messages In MessageBox listMessage.Items.Add(""+recivedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
System.Windows.Forms.MessageBox.Show(exp.ToString());
}
}
private void Connect_Click(object sender, EventArgs e)
{
try
{
epLocal = new IPEndPoint(IPAddress.Parse(IPMe.Text), Convert.ToInt32(PortMe.Text)); //MyPort And MyIP Make Port to Int32
sck.Bind(epLocal); //Socket Bind To epLocal
epRemote = new IPEndPoint(IPAddress.Parse(IpConnectingTo.Text), Convert.ToInt32(PortConnectingTo.Text)); //MyPort And MyIP Make Port to Int32
sck.Connect(epRemote); //Socket Bind To epRemote
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
Connect.Text = "Connected"; //Set Text To Connected
Connect.Enabled = false; //Disabled (Gray)
Send.Enabled = true; //Enable Send Button
TextBoxSendMessages.Focus(); //Set Focus To This!
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
private void Send_Click(object sender, EventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
string nickandtext = NickNameMe.Text + ": " + TextBoxSendMessages.Text;
msg = enc.GetBytes(nickandtext); //Messages The Sum Of Both
//msg = enc.GetBytes(NickNameMe.Text + TextBoxSendMessages.Text);
sck.Send(msg); //Send Message In Bytes
MessageBox.Items.Add(NickNameMe.Text + ": " + TextBoxSendMessages.Text); //See yourself msg in msgbox
TextBoxSendMessages.Clear(); //Clear Text Message Box
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
private void IPMe_TextChanged(object sender, EventArgs e)
{
}
private void MessageBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
Picture of program:

Using sockets to send information from server to client

I've setup a server and a client, trying to send a string from my server to my client.
As it appears, my client does not received the message, and as I'm new to networking I can't seem to find the error.
My server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Server
{
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
class Program
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public static ManualResetEvent sendDone = new ManualResetEvent(false);
public static void StartListening()
{
byte[] bytes = new byte[1024];
IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostEntry.AddressList[0];
IPEndPoint localEndPointOut =
new IPEndPoint(ipAddress, 22222);
Console.WriteLine(ipAddress);
Socket listenerOut = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
StateObject state = new StateObject();
Socket handler = state.workSocket;
try
{
listenerOut.Bind(localEndPointOut);
listenerOut.Listen(100);
while (true)
{
allDone.Reset();
listenerOut.BeginAccept(new AsyncCallback(outputCallback), listenerOut);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress enter to continue...");
Console.Read();
}
public static void outputCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0,
StateObject.BufferSize, 0,
new AsyncCallback(outputStream), state);
}
public static void outputStream(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
byte[] byteData = Encoding.ASCII.GetBytes("test");
while (true)
{
try
{
handler.Send(byteData, SocketFlags.None);
}
catch
{
Console.WriteLine("Client forcebly closed.");
}
}
}
static void Main(string[] args)
{
StartListening();
Console.ReadKey();
}
}
}
And my client:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace OutputClient
{
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 256;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
class Program
{
private const int port = 22222;
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
private static String response = String.Empty;
private static void StartClient()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Socket client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
Receive(client);
receiveDone.WaitOne();
Console.WriteLine(response);
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void Main(string[] args)
{
StartClient();
Console.ReadKey();
}
}
}
Currently I'm using the Socket.Send method on my server, I also tried using Socket.BeginSend, but with same result.
I don't get any errors, there just seem to be data being send. The server registers the client however.
Your server calls BeginReceive and in its handler (outputCallback) it attempts to send data. This means that the server won't send data until it has received something from the client first.
The client however never sends any data; only when you close the client your server will receive a 0-byte message and start sending data (which of course isn't picked up by the client anymore).

C# server and client not working

I have been making a C# server and client for a game. I have used many resources to try to create something successful. So far, the client can send stuff to the server and the server can receive them, but I want to be able to send stuff to the client. Also, I don't know what happened, but my server code suddenly stopped printing to console or something. I am new at this and any help is needed. I think I programmed both client and server to be able to send and receive, but something isn't right...
Note: I am using a cmd compiler running an old version of the .NET (but the code still compiles), any help on getting visual studio working to build/compile the code would also be nice :)
Client-side:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class Program
{
static Boolean done = false;
static void Main(string[] args)
{
Boolean exception_thrown = false;
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse("ip-goes-here");
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 27020);
Console.WriteLine("Enter text to broadcast via UDP.");
Console.WriteLine("Enter a blank line to exit the program.");
Thread listenerT = new Thread(new ThreadStart(Program.listener));
listenerT.Start();
while (!done)
{
Console.WriteLine("Enter text to send, blank line to quit");
string text_to_send = Console.ReadLine();
if (text_to_send.Length == 0)
{
done = true;
listenerT.Abort();
}
else
{
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
Console.WriteLine("sending to address: {0} port: {1}",
sending_end_point.Address,
sending_end_point.Port);
try
{
sending_socket.SendTo(send_buffer, sending_end_point);
}
catch (Exception send_exception)
{
exception_thrown = true;
Console.WriteLine(" Exception {0}", send_exception.Message);
}
if (exception_thrown == false)
{
Console.WriteLine("Message has been sent to the broadcast address");
}
else
{
exception_thrown = false;
Console.WriteLine("The exception indicates the message was not sent.");
}
}
}
}
static void listener()
{
int listenPort = 27020;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
string received_data;
byte[] receive_byte_array;
try
{
while (!done)
{
Console.WriteLine("Waiting for broadcast");
receive_byte_array = listener.Receive(ref groupEP);
Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
Console.WriteLine("data follows \n{0}\n\n", received_data);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Server side:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class UDPListener
{
private const int listenPort = 27020;
//static Boolean done = false;
static IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
static UdpClient udpServer = new UdpClient(27020);
static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 27020);
static byte[] data = udpServer.Receive(ref remoteEP); // listen on port 11000
static IPAddress send_to_address = IPAddress.Parse("10.240.0.1");
static IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 27020);
public static void Main()
{
Console.WriteLine("Begin listening sequence");
while (true)
{
data = udpServer.Receive(ref groupEP);
Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
send_to_address = IPAddress.Parse(groupEP.ToString());
Thread listenerT = new Thread(new ThreadStart(UDPListener.sender));
listenerT.Start();
String received_data = Encoding.ASCII.GetString(data, 0, data.Length);
Console.WriteLine(received_data);
}
}
static void sender()
{
while (true)
{
Console.WriteLine("Enter text to send, blank line to quit");
string text_to_send = Console.ReadLine();
if (text_to_send.Length == 0)
{
//done = true;
}
else
{
byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);
Console.WriteLine("sending to address: {0} port: {1}",
sending_end_point.Address,
sending_end_point.Port);
udpServer.Send(send_buffer, 0, remoteEP); // reply back
}
}
}
}
Nevermind, a friend of mine figured it out. You can find the final code in a github repo called something like flaming leaf server

webcam frame in a class to serialize and send

I'm trying to serialize a MessageData class and send it by network.
This class contain picture in bitmap that I need to display on a form.
The transmitted bitmap it's a frame that a webcam need to transmit several times each second by network to a WinForm.
This program it's a test and in future will be splitted in two parts, client part with receiver method and winform, and a server part with webcam and sender method.
Actually the Serializing and sending-receiving of the object-picture is not working, the winform is not showing any image if I force picture to pass from the serializing-network process instad of get it directly.
The webcam frames are managed with the Emgu.CV library, and locally it's working very well, but not by remote with the serialization sending of the frames.
All that follow is inside the namespace Idea:
[Serializable]
public class MessageData {
public MessageData(Bitmap img){
Picture = img;
}
public static Bitmap Picture { get; set; }
}
[Serializable]
public class MessageSendData {
public MessageSendData(Bitmap img){
Picture = img;
}
public static Bitmap Picture { get; set; }
}
public partial class Idea : Form
{
//declaring global variables
private Capture capture; //takes images from camera as image frames
private bool captureInProgress; // checks if capture is executing
private TcpListener ascolto;
Bitmap bitmapricevuto;
public Idea()
{
InitializeComponent();
}
private void Idea_Load(object sender, EventArgs e)
{
}
private void ProcessFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> ImageFrame = capture.QueryFrame(); //line 1
// CamImageBox.Image = byteArrayToImage(MyImageBytes(ImageFrame.ToBitmap()));
// CamImageBox.Image = ImageFrame.ToBitmap();
Thread r = new Thread(Ricevi);
r.Start();
MessageSendData.Picture = ImageFrame.ToBitmap();
Thread s = new Thread(Spedisci);
s.Start();
lock (MessageData.Picture){
CamImageBox.Image = MessageData.Picture;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
#region if capture is not created, create it now
if (capture == null)
{
try
{
capture = new Capture();
}
catch (NullReferenceException excpt)
{
MessageBox.Show(excpt.Message);
}
}
#endregion
if (capture != null)
{
if (captureInProgress)
{ //if camera is getting frames then stop the capture and set button Text
// "Start" for resuming capture
btnStart.Text = "Start!"; //
Application.Idle -= ProcessFrame;
}
else
{
//if camera is NOT getting frames then start the capture and set button
// Text to "Stop" for pausing capture
btnStart.Text = "Stop";
Application.Idle += ProcessFrame;
}
captureInProgress = !captureInProgress;
}
}
private void ReleaseData()
{
if (capture != null)
capture.Dispose();
}
public static void Ricevi()
{
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(address, 8585);
listener.Start();
Bitmap mia;
try
{
using (TcpClient client = listener.AcceptTcpClient())
{
NetworkStream stream = client.GetStream();
IFormatter formatter = new BinaryFormatter();
while (true)
{
lock (MessageData.Picture){
MessageData.Picture = (Bitmap)formatter.Deserialize(stream);
}
}
}
}
catch(Exception ex) { }
return;
}
public static void Spedisci()
{
IPAddress address = IPAddress.Parse("127.0.0.1");
TcpClient client = new TcpClient();
try
{
client.Connect(address, 8585);
// Retrieve the network stream.
NetworkStream stream = client.GetStream();
IFormatter formatter = new BinaryFormatter();
while(true)
{
lock (MessageSendData.Picture) {
formatter.Serialize(stream, MessageSendData.Picture);
//Thread.Sleep(1000);
}
}
}
catch (Exception ex) { }
}
/*
public byte[] MyImageBytes(Image MyImage)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(MyImage, typeof(byte[]));
}
public Image byteArrayToImage(byte[] bytesArr)
{
MemoryStream memstr = new MemoryStream(bytesArr);
Image img = Image.FromStream(memstr);
return img;
}
*/
}
}
'
I've realized two methods: 1-First method convert the bitmap in a byte array. 2-Second method convert the byte array in a bitmap. Testing them directly without send the converted bytes by tcp network I see that all software are working. Now I've created two methods "Invia" and "Ricevi" that are sending and receiving with async methods the bytearrays by spliting them in stream of a length of 1024 each. My issue on compiling it's about the Async Task methods returned types. How to fix this threads Task async issues?
'
private void ProcessFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> ImageFrame = capture.QueryFrame();
invia(MyImageBytes(ImageFrame.ToBitmap()));
CamImageBox.Image = ricevi();
}
public byte[] MyImageBytes(Image MyImage)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(MyImage, typeof(byte[]));
}
'
Send (Invia) and Receive(Ricevi) methods last version here showed below are using the chars converted to bytes array and appended to the bitmap bytes array for send and receive the bitmap. Actually I've issues during compiling:
public static void invia(byte[] bytetosend)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
var mahByteArray = new ArrayList<byte>();
mahByteArray.AddRange(bytetosend);
string eof = "<EOF>";
mahByteArray.Insert(0, Convert.ToByte(eof)); // Adds eof bytes to the beginning.
byte[] msg = mahByteArray.ToArray();
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
public static void ricevi()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
var scambioArray = new ArrayList();
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
string eofr = "<EOF>";
byte[] trova = Convert.ToByte(eofr);
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
if (bytes.IndexOf(trova))
{
var mahByteArray = new ArrayList();
mahByteArray.AddRange(bytes);
mahByteArray.Remove(trova);
bytes = mahByteArray.ToArray();
break;
}
scambioArray.AddRange(bytes);
}
// Echo the data back to the client.
byte[] msg = scambioArray.ToArray();
MessageData.Picture = byteArrayToImage(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Try something like this
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static void invia(byte[] bytetosend)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
var mahByteArray = new List<byte>();
mahByteArray.AddRange(bytetosend);
string eof = "<EOF>";
mahByteArray.Insert(0, Convert.ToByte(eof)); // Adds eof bytes to the beginning.
byte[] msg = mahByteArray.ToArray();
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void ricevi()
{
// Data buffer for incoming data.
List<byte> bytes = (new Byte[1024]).ToList();
List<byte> scambioArray = new List<byte>();
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
string eofr = "<EOF>";
List<byte> trova = Encoding.UTF8.GetBytes(eofr).ToList();
// An incoming connection needs to be processed.
while (true)
{
bytes = (new byte[1024]).ToList();
int bytesRec = handler.Receive(bytes.ToArray());
if (bytes.Contains(trova[0]))
{
List<byte> mahByteArray = new List<byte>();
mahByteArray.AddRange(bytes);
mahByteArray.Remove(trova[0]);
bytes = mahByteArray.ToArray().ToList();
break;
}
scambioArray.AddRange(bytes);
}
// Echo the data back to the client.
byte[] msg = scambioArray.ToArray();
MemoryStream stream = new MemoryStream(msg);
MessageData.Image = Image.FromStream(stream);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
​

Categories

Resources