Reputation: 29
I am working on an application where I need to send a command over a socket connection and then receive the data it sends back. I am having difficulty getting anything back from the server after sending my command. I was told initially to "end the package with a binary 0", and I think this is what might be throwing me off as I am not really sure how to do this in c#. Here is some source code:
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(remoteEp);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
byte zero = Encoding.Default.GetBytes("0")[0];
byte[] msg = Encoding.ASCII.GetBytes("PACK_ALARM.ALARM_GETCOUNTI,294,0" + zero);
int bytesSent = sender.Send(msg);
int bytesReceived = sender.Receive(bytes);
Console.WriteLine("Test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesReceived));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.Write("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("Socket Exception : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Upvotes: 0
Views: 529
Reputation: 63772
You're not sending a binary zero. You're sending the ASCII representation of the character '0'
, converted to a number, converted to a string.
Instead, just do this:
byte[] msg = Encoding.ASCII.GetBytes("PACK_ALARM.ALARM_GETCOUNTI,294,0\0");
The \0
is a literal for the null character - binary zero.
Also, note that TCP is a stream protocol, not a message-based protocol. You're supposed to keep Receive
ing in a loop until you get the whole message. For short, infrequent messages, your code might work (unreliably), but any real communication is going to result in a horrible mess.
Upvotes: 1