Hanselman Hanselman - 1 month ago 9
C# Question

C# Receive Data from Socket and put it in a String?

I have a socket server and try to receive a string from client.

Client is perfect and when I use this

Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine(k);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));

ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));


All is okay and I get my string in the console.

But how can I get now my receive into a string so I can use it in a switch case?

Like this:

string action = Convert.ToChar(b[i]);


Error:


The Name i isn't in the current context.
its the only Error Message i get.

Answer

Assuming s is a Socket object on which you call receive, you get an byte[] back. To convert this back to a string, use the appropiate encoding, e.g.

string szReceived = Encoding.ASCII.GetString(b);

Edit: Since the buffer b is always 100 bytes, but the actual number of bytes received varies with each connection, one should use the return value of the Socket.Receive() call to only convert the actual number of received bytes.

byte[] b = new byte[100];
int k = s.Receive(b);
string szReceived = Encoding.ASCII.GetString(b,0,k);