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.
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();
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With