I've written a small tcp client that is supposed to send a command off to a server I wrote and receive data back. The server sends multiple sets of data over a single connection. There is nothing wrong with the server (that I can identify) and I have a high confidence of that because it's in a language I know very well. However, the client itself which is written in c# is not behaving as expected. Could someone please give me some pointers on what to do to improve it? Currently it does not resolve any data at all. The server does not complain that the connection has been cut either. So the client has to be exiting early somehow.
public static string SendMessage(String callingFunction, String parameters)
{
try{
TcpClient tcpClient = new TcpClient();
tcpClient.Client.ReceiveTimeout = 1000*5;
string message = "FUNC{" + callingFunction + "}" + parameters + "END";
byte[] msg = Encoding.ASCII.GetBytes(message);
int numOfBytesRead = 0;
tcpClient.Connect("127.0.0.1", 65432);
NetworkStream stream = tcpClient.GetStream();
MemoryStream memStream = new MemoryStream();
stream.Write(msg, 0, msg.Length);
do
{
try{
byte[] response = new byte[1024];
numOfBytesRead = stream.Read(response, 0, response.Length);
memStream.Write(response, 0, numOfBytesRead);
}
catch
{
numOfBytesRead = 0;
}
} while(numOfBytesRead > 0);
StreamReader sr = new StreamReader(memStream);
string f = sr.ReadToEnd().ToString();
return "hello"+numOfBytesRead.ToString()+"goodbye";
}
catch (Exception e){
Console.WriteLine(e.ToString());
return "";
}
}
Updated code
TcpClient tcpClient = new TcpClient();
tcpClient.Client.ReceiveTimeout = 1000*5;
string message = "FUNC{" + callingFunction + "}" + parameters + "END";
byte[] msg = Encoding.ASCII.GetBytes(message);
tcpClient.Connect("127.0.0.1", 65432);
NetworkStream stream = tcpClient.GetStream();
MemoryStream memStream = new MemoryStream();
stream.Write(msg, 0, msg.Length);
stream.CopyTo(memStream);
StreamReader sr = new StreamReader(memStream);
string f = sr.ReadToEnd().ToString();
return "hello"+f+"goodbye";