这是从客户端接收值的函数。但问题是我只收到一次。无论我发送多少次数据,MainWindows 上的标签都只会更改一次。
我在这里做错了什么?
private void HandleClientComm(object client)
{
tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
break;
}
if (bytesRead == 0)
{
break;
}
if (String.IsNullOrWhiteSpace(data))
{
ASCIIEncoding encoder = new ASCIIEncoding();
data = encoder.GetString(message, 0, bytesRead);
MainWindow.Change(data);
tcpClient.Close();
}
tcpClient.Close();
}
在客户端,我有以下示例:
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1", 8001);
Console.WriteLine("Connected");
while (true)
{
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
stm.Flush();
Console.WriteLine("Sent.....");
}
tcpclnt.Close();
Console.Read();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
只是一个快速的例子,所以当我输入字符串名称时,值第一次改变但是当我第二次输入或者如果我退出客户端程序并重新输入没有任何变化时,标签内容的值等于第一次发送价值。