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 ...
服务器
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( ));
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
正如道格拉斯所指出的,缓冲(messageBytes)与先前的一段话相左。 我最后用这一服务器代码(我贴出整个代码,因为这可能对其他人有用):
namespace Gateway
{
class Program
{
static void Main(string[] args)
{
int requestCount = 0;
TcpListener serverSocket = new TcpListener(IPAddress.Any, 8888);
serverSocket.Start();
LogToConsole("服务器 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);
}
}
}