Hanselman
Hanselman

Reputation: 171

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

I have a socket server and am trying to receive a string from the client.

The 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.

Upvotes: 7

Views: 36142

Answers (3)

Rodrigo Reis
Rodrigo Reis

Reputation: 1117

This way no need set buffer size, it fits to response:

public static byte[] ReceiveAll(this Socket socket)
    {
        var buffer = new List<byte>();

        while (socket.Available > 0)
        {
            var currByte = new Byte[1];
            var byteCounter = socket.Receive(currByte, currByte.Length, SocketFlags.None);

            if (byteCounter.Equals(1))
            {
                buffer.Add(currByte[0]);
            }
        }

        return buffer.ToArray();
    }

Upvotes: 5

Masoud Siahkali
Masoud Siahkali

Reputation: 5351

Init socket

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdd = System.Net.IPAddress.Parse(m_ip);
IPEndPoint remoteEP = new IPEndPoint(ipAdd, m_port);

Connect socket

socket.Connect(remoteEP);

Receive from socket

byte[] buffer = new byte[1024];
int iRx = socket.Receive(buffer);
char[] chars = new char[iRx];

System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String recv = new System.String(chars);

Send message

byte[] byData = System.Text.Encoding.ASCII.GetBytes("Message");
socket.Send(byData);

Close socket

socket.Disconnect(false);
socket.Close();

Upvotes: 4

Maximilian Gerhardt
Maximilian Gerhardt

Reputation: 5353

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); 

Upvotes: 4

Related Questions