1

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";
  • 1
    Please can you go into more detail about what is wrong. For example: what happens if you step through the code with the debugger? How have you verified that the client is at fault? – ProgrammingLlama May 26 '22 at 01:51
  • @DiplomacyNotWar Well, numOfBytesRead shows 0. f is empty. The loop doesn't time out. Or (in different versions of the code - without timeout being modified) times out too early. I can see the server sending the data yet the client just returns after the very first response from the client (in a different version of the code). – wookieluvr49 May 26 '22 at 01:54
  • @DiplomacyNotWar Yes I have verified that the server *is* sending off data and the client *is not* showing the data. I tested it earlier by cutting off the server by receiving only one response. The server threw an error that the connection was dead. However now the server does not show a dead connection. – wookieluvr49 May 26 '22 at 02:02
  • 1
    To me it sounds like you're dropping into your `catch`, and that's setting the `numOfBytesRead` to 0. If it's genuinely `.Read` is returning that then you've been disconnected. – ProgrammingLlama May 26 '22 at 02:03
  • @DiplomacyNotWar How would you go about cleanly exiting after receiving all of the data? I read online of a few different ways. This way seemed to be the only one that allowed me to accept arbitrary numbers of "sent" data over a single connection. – wookieluvr49 May 26 '22 at 02:05
  • 1
    If a `NetworkStream`'s `Read` method returns 0 then you can conclude that the server has closed the question and you can break out of the loop. If the server always closes the connection after sending the data, you could perhaps use `stream.CopyTo(memStream);` instead of your loop. – ProgrammingLlama May 26 '22 at 02:07
  • @DiplomacyNotWar see updated initial post. It appears to work in that it doesn't crash but still an empty string. – wookieluvr49 May 26 '22 at 02:13
  • 1
    `memStream.Position = 0;` after reading? Otherwise you're reading from the end of the stream, which has no data because it's at the end. – ProgrammingLlama May 26 '22 at 02:17
  • 1
    I've marked your question as a duplicate of a similar question with essentially the same issue. I'm glad we got it sorted. :) – ProgrammingLlama May 26 '22 at 02:31

0 Answers0