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
There's a few things here;
var bytes = sock.Receive(buffer); (and use bytes for both the EOF test, and for how many bytes to process)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)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"If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With