大家,我正在尝试编写一个循环来从后台线程中连接的套接字中读取。但它只接收第一条消息。我已经搜索了一段时间以找到原因。但还是想不通。我知道有些人遇到了同样的问题。然而,他们的原因似乎不同。我希望有人能帮助我。
private void setPort_Click(object sender, EventArgs e)
{
SetupTcpListener = new Task(() =>
{
try
{
Int32 Port;
Int32.TryParse(portNum.Text, out Port);
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, Port);
server.Start(10);
Tclient = server.AcceptTcpClient();
Console.WriteLine("Connected");
}
catch (SocketException exc)
{
Console.WriteLine("SocketException: {0}", exc);
}
NetworkStream tstream = Tclient.GetStream();
int t = 0;
while (true)//the first loop: WriteLine a signal when read sth
//read first message:"Get 0"
//read second message:"Get 1"
//and so on
{
t++;
int i = 0;
while (i <= 0)//the second loop is trying to read until get sth.
//when it get sth, the first while loop continue,and print a "Get t"
//t means how many times it has read a messsage.
{
i = tstream.Read(ReadBuffer,0,40);
}
Console.WriteLine("Get "+ t.ToString());
}
});
SetupTcpListener.Start();
}