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
- 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. - 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.