Home > Software engineering >  Receiving Data from Machine using Socket
Receiving Data from Machine using Socket

Time:09-27


I am very new in Socket Programming.
I am using the following code to receive incoming data from a pathology machine.
 byte[] buffer = new byte[2048];

        IPAddress ipAddress = IPAddress.Parse(SERVER_IP);
        IPEndPoint localEndpoint = new IPEndPoint(ipAddress, PORT_NO);

        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            sock.Connect(localEndpoint);
        }
        catch (Exception ex)
        {
            throw ex;
        }

        int recv = 0;
        string Printed = string.Empty;
        StringBuilder sb = new StringBuilder();
        while ((recv = sock.Receive(buffer)) > 0)
        {
            if (sock.Receive(buffer).ToString().Length > 1) // I used this line because it's receiving some garbage value all the time.
            {
                sb.Append(Encoding.UTF8.GetString(buffer));
            }
            else
            {
                if (sb.Length > 50 && Printed == string.Empty)
                {
                    Console.WriteLine(sb);
                    Printed = "Y";
                }
            }
        }

Issues I am facing

  1. My program is not receiving complete data. Maybe because of this line if (sock.Receive(buffer).ToString().Length > 1). But I used this line because it's always receiving something.
  2. My program goes to endless loop. I am looking for the program which should stop for sometime after receiving the data and start listening again for new incoming data.

CodePudding user response:

There's a few things here;

  1. you need to store the read count, and use only that many bytes, i.e. var bytes = sock.Receive(buffer); (and use bytes for both the EOF test, and for how many bytes to process)
  2. we can't use ToString().Length > 1 here, because it is an integer and every integer, as a string, has a non-zero length; instead, simply: if (bytes > 0) (minutiae: there is a scenario where an open socket can return zero without meaning EOF, but... it doesn't apply here)
  3. even for a text protocol, you can't necessarily simply use Encoding.UTF8.GetString(buffer, 0, bytes), because UTF8 is a multi-byte encoding, meaning: you might have partial characters; additionally, you don't yet know whether that is one message, half a message, or 14 and a bit messages; you need to read about the protocol's "framing" - which might simply mean "buffer bytes until you see a newline ('\n') character, decode those buffered bytes via the encoding, process that message, and repeat"
  • Related