I’ve both a client and a server communicating through TCP.
The client uses the NetworkStream to send info to the server that reads it back, then the process continues until the user wants to exit and close the connection. The problem is that the NetworkStream is dirty with a previous write. So let’s suppose the client sends the string “aa “during the first time, and “b” during the second. On the second read the server will get “ba”. What’s missing here? Shouldn’t the NetworkStream be consumed during the server reads? Here`s the relevant code …
Server
while (true)
{
try
{
NetworkStream clientStream = tcpClient.GetStream();
bytesRead = clientStream.Read(messageBytes, 0, messageBytes.Length);
}
catch (Exception ex)
{
LogToConsole(clientEndPoint, String.Format("[ERROR] Exception: {0}", ex.Message));
break;
}
if (bytesRead == 0)
{
LogToConsole(clientEndPoint, "Client has disconnected");
break;
}
messageCounter++;
string message = Encoding.ASCII.GetString(messageBytes);
message = message.Substring(0, message.IndexOf('\0'));
LogToConsole(clientEndPoint, String.Format(" >> [{0}] Message received: {1}", messageCounter, message));
}
CLIENT
string infoToSend = null;
do
{
Console.Write(" >> Info to send: ");
infoToSend = Console.ReadLine();
if (!String.IsNullOrEmpty(infoToSend))
{
NetworkStream serverStream = client.GetStream();
byte[] buffer = Encoding.ASCII.GetBytes(infoToSend);
serverStream.Write(buffer, 0, buffer.Length);
serverStream.Flush();
}
} while (!String.IsNullOrEmpty(infoToSend));
SOLUTION
As Douglas spotted, the buffer (messageBytes) was dirty with a previous read. I ended up with this code for the server (I posted the entire code as it might be useful for somebody else):
namespace Gateway
{
class Program
{
static void Main(string[] args)
{
int requestCount = 0;
TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
serverSocket.Start();
LogToConsole("Server Started. Waiting for clients ...");
while ((true))
{
try
{
TcpClient client = serverSocket.AcceptTcpClient();
requestCount++;
LogToConsole(String.Format("Connection from {0} accepted. Request #{1}", client.Client.RemoteEndPoint.ToString(), requestCount));
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientConnection));
clientThread.IsBackground = true;
clientThread.Start(client);
LogToConsole(String.Format("Thread #{0} created to handle connection from {1}", clientThread.ManagedThreadId, client.Client.RemoteEndPoint.ToString()));
LogToConsole("Waiting for next client ...");
}
catch (Exception ex)
{
LogToConsole(ex.ToString());
break;
}
}
}
static void HandleClientConnection(object client)
{
TcpClient tcpClient = (TcpClient)client;
byte[] messageBytes = new byte[1024];
int bytesRead;
int messageCounter = 0;
string clientEndPoint = tcpClient.Client.RemoteEndPoint.ToString();
while (true)
{
try
{
NetworkStream clientStream = tcpClient.GetStream();
bytesRead = clientStream.Read(messageBytes, 0, messageBytes.Length);
}
catch (Exception ex)
{
LogToConsole(clientEndPoint, String.Format("[ERROR] Exception: {0}", ex.Message));
break;
}
if (bytesRead == 0)
{
LogToConsole(clientEndPoint, "Client has disconnected");
break;
}
messageCounter++;
string message = Encoding.ASCII.GetString(messageBytes, 0, bytesRead);
LogToConsole(clientEndPoint, String.Format(" >> [{0}] Message received: {1}", messageCounter, message));
}
LogToConsole(clientEndPoint, "Closed connection to client");
tcpClient.Close();
}
static void LogToConsole(string clientEndPoint, string message)
{
int threadId = Thread.CurrentThread.ManagedThreadId;
string time = DateTime.Now.ToString("HH:mm:ss");
Console.WriteLine("{0} [{1}, {2}] {3}", time, threadId, clientEndPoint, message);
}
static void LogToConsole(string message)
{
int threadId = Thread.CurrentThread.ManagedThreadId;
string time = DateTime.Now.ToString("HH:mm:ss");
Console.WriteLine("{0} [{1}] {2}", time, threadId, message);
}
}
}
The above call decodes the entire buffer each time, despite that each message would only be written to the first n bytes of it (where n is the message length). Your first message, “aa”, is written to the first two bytes of the buffer. Your second message, “b”, is written to just the first byte, overwriting the first ‘a’ character but leaving the second ‘a’ intact. This is why the buffer appears to contain “ba” after your second message.
You can trivially solve this by changing the call above to:
However, your code would still be susceptible to another issue:
NetworkStream.Readonly reads as much data as is currently available. If the client is still transmitting, then it might return a partial message. So your server might read the two messages as “a” and “ab”.In your case, since you seem to be transmitting single-line text messages only, you could wrap the
NetworkStreamin aStreamReaderin the server, and in aStreamWriterin the client. Then, simply callStreamReader.ReadLineon the server, andStreamWriter.WriteLineon the client.ReadLinewill keep reading until it encounters a newline, and will returnnullwhen the end of the stream is reached.Server:
Client:
This solution will not work if your client can send newlines within your messages.