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;
}
}
Issue I am facing…
- Machine is sending huge amount of data and gets busy and disconnects from program after some time.
- How can I start receiving data again? Is there any receiving event which fires automatically for incoming data?
2
Answers
If you are dealing with TCP/IP communication, using a
NetworkStream
(as commented) along with aStreamReader
can simplify the process of reading incoming data.That would abstract away some of the lower-level byte handling (and the code is simpler).
The "Process the received message" part means understanding the protocol used by your pathology machine. If the machine uses a standard protocol (HTTP, TLS, SMTP, etc.), you should use a library or framework that supports that protocol out of the box. That way, you will be able to handle messages according to the protocol’s specifications, including reconnections and data transmission.
For protocols that do not support signaling for "send next message," you might indeed need to close and reopen the connection. But this should be considered a last resort, as it is not efficient and might not be supported by all devices.
As commented, considering asynchronous communication (e.g., using
BeginReceive
andEndReceive
orasync
/await
withNetworkStream
) to improve performance and responsiveness, especially if you are dealing with large volumes of data.See also "Using Asynchronous Methods in ASP.NET 4.5"
There’s something wrong with your "pattern". The usual pattern is to "send a request"; and then "read the response". You should be identifying the actual machine you’re working with since it will document what "protocols" it actually supports; AND the amount of data it will return in response to a given request; so you have an idea of what you’re dealing with.
The cases where a device just "transmits" without actually being asked to, are very few.