我正在开发一个 Windows 应用程序(服务器-客户端通信),其中服务器不断向客户端发送字符串消息,客户端通过网络流读取该消息。从网络流客户端读取消息后,刷新网络流,但旧消息仍保留在网络流中。我认为这是由于在服务器端的网络流中不断写入消息而发生的。
代码客户端:
clientSocket.Connect("192.XXX.X.XX", 8888);
label1.Text = "Client Socket Program - Server Connected ...";
NetworkStream serverStream = clientSocket.GetStream();
string returndata = "";
while ((true))
{
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
returndata = System.Text.Encoding.ASCII.GetString(inStream);
serverStream.Flush();
}
服务器端 :
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
NetworkStream networkStream = null;
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
networkStream = clientSocket.GetStream();
Byte[] sendBytes = Encoding.ASCII.GetBytes(task);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
请告诉我如何解决这个问题?