while (true)
{
if (tcpListener.Pending() == false)
{
//...省略
}
else
{
tcpClient = tcpListener.AcceptTcpClient();
NetworkStream stream = tcpClient.GetStream();
bool closed = false;
byte[] testByte = new byte[1];
while (tcpClient.Connected && !closed)
{
if (tcpClient.Available > 0)
{
//讀資料...
}
try
{
if (tcpClient.Connected && tcpClient.Client.Poll(30, SelectMode.SelectRead))
closed = tcpClient.Client.Receive(testByte, SocketFlags.Peek) == 0;
}
catch(Exception ex)
{
closed = true;
}
Thread.Sleep(20);
}
stream.Close();
}
}
請問一下前輩為何這樣的作法,當server端先連線127.0.0.1 ,client後連線,tcpClient.Available會一直為0,可是雙方卻是連線正常,但是當client先嘗試持續連線連上後,server在連上雙方持續一來一往溝通就都正常為何呢?也就是說另一方面,我也希望在server與client正常連接後,client斷線後,client再連上會是正常往來溝通
1.改用 NetworkStream.DataAvailable 屬性來檢查是否有資料可供讀取,而不是使用 tcpClient.Available。
2.改用 SelectMode.SelectRead 代替 SelectMode.SelectWrite 可以更好地檢查是否有資料可讀取。
3.有可能是由於你的等待時間不足,因此資料尚未完全進入網路串流,所以在 client 連接到 server 後,等待一段時間,再進行讀取。
while (true)
{
if (tcpListener.Pending() == false)
{
// ...省略
}
else
{
tcpClient = tcpListener.AcceptTcpClient();
NetworkStream stream = tcpClient.GetStream();
bool closed = false;
byte[] testByte = new byte[1];
// 等待一段時間,以確保資料已進入網路串流
Thread.Sleep(1000);
while (tcpClient.Connected && !closed)
{
if (stream.DataAvailable)
{
// 讀資料...
}
try
{
// 檢查是否有資料可以讀取, 使用 SelectMode.SelectRead 代替 SelectMode.SelectWrite 可以更好地檢查是否有資料可讀取。
if (tcpClient.Connected && tcpClient.Client.Poll(30, SelectMode.SelectRead))
{
int receivedByte = tcpClient.Client.Receive(testByte, SocketFlags.Peek);
if (receivedByte == 0)
closed = true;
}
}
catch (Exception ex)
{
closed = true;
}
Thread.Sleep(20);
}
stream.Close();
}
}