大家好,我正在嘗試編寫一個循環來讀取後臺線程中連接的套接字。但它只收到第一條消息。我搜索了一段時間來找到原因。但仍然無法弄清楚。我知道有些人遇到了同樣的問題。但是,他們的原因似乎不同。我希望有人能幫助我。套接字只讀第一次工作
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();
}
您的讀取語句返回讀取的字節數。所以如果你成功地讀了一些東西,我被設置爲一個大於零的數字......而你的while循環是爲i <= 0。 – andrew 2013-02-13 02:09:02
這就是我想要的,如果它Read()某事,它會打印一條消息,if不要,只是做一次(我<= 0)。但tstream.Read()只能在第一次正常工作。 – xyloid 2013-02-13 02:39:11
@xlyloid這是因爲你只執行一次。再次閱讀評論和答案。 – EJP 2013-02-13 02:47:35