[英]networkStream.Read is blocking
我正在編寫一個將與服務器連接的簡單應用程序。 但是我也想發送簡單的聊天命令(請參閱下面的Console.ReadLine
)。 但是,此腳本不會到達string Message = Console.ReadLine();
因為它被阻止在bytesRead = clientStream.Read(message, 0, 4096);
。
我想繼續執行此腳本,但是如果有字節輸入,它應該對其進行處理(就像現在所做的那樣),如果沒有字節輸入,則應該通過腳本並等待用戶輸入)。 如何做到這一點?
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
// Blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception)
{
// A socket error has occured
break;
}
if (bytesRead == 0)
{
// The client has disconnected from the server
break;
}
// Message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
// Output message
Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
// Return message
string Message = Console.ReadLine();
if (Message != null)
{
byte[] buffer = encoder.GetBytes(Message);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
您可以嘗試使用DataAvailable屬性。 它會告訴您套接字上是否有任何等待。 如果為假,請不要執行Read
調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.