networkStream.Read被阻止 [英] networkStream.Read is blocking
问题描述
我正在编写一个将与服务器连接的简单应用程序。但是,我也想发送简单的聊天命令(请参见下面的 Console.ReadLine
)。但是,此脚本不会到达 string消息= Console.ReadLine();
,因为它在 bytesRead = clientStream.Read(message,0, 4096);
。
I'm writing a simple application which will connect with a server. However I want to send simple chat commands aswell (see Console.ReadLine
below). However this script won't get to string Message = Console.ReadLine();
since it's blocked at bytesRead = clientStream.Read(message, 0, 4096);
.
我想继续执行此脚本,但是如果有字节输入,它应该对其进行处理(就像现在所做的那样),如果没有字节输入,则应通过脚本并等待用户输入)。
I want to continue this script, but if there's bytes incoming, it should process them (like it's doing now) and if no bytes are incoming, it should go through the script and wait for user input). How can this be achieved?
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();
}
推荐答案
您可以尝试使用<一个href = http://msdn.microsoft.com/zh-cn/library/system.net.sockets.networkstream.dataavailable.aspx rel = noreferrer> DataAvailable 属性。它将告诉您套接字上是否有任何等待。如果错误,请不要执行 Read
调用。
You could try using the DataAvailable property. It'll tell you whether there's anything waiting on the socket. If it's false, don't do the Read
call.
这篇关于networkStream.Read被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!