Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving Data from Machine using Socket


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;
        }

        while (true)
        {                
            int bytesRec = sock.Receive(buffer);
            data += Encoding.ASCII.GetString(buffer, 0, bytesRec);
            if (data.IndexOf("<EOF>") > -1)
            {
                break;
            }
        }

Issues I am facing

  1. Machine is sending huge amount of data and gets buys and disconnects from program after some time.
  2. How can I start receiving data again ? Is there any receiving event which fires automatically for incoming data?

    What am I doing wrong here?
like image 735
Shaiwal Tripathi Avatar asked Oct 20 '25 16:10

Shaiwal Tripathi


1 Answers

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"
like image 87
Marc Gravell Avatar answered Oct 23 '25 05:10

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!