Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

sockets

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.

like image 234
Hanselman Avatar asked Sep 05 '15 11:09

Hanselman


2 Answers

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();
    }
like image 127
Rodrigo Reis Avatar answered Sep 28 '22 01:09

Rodrigo Reis


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();
like image 34
Masoud Siahkali Avatar answered Sep 28 '22 03:09

Masoud Siahkali