我从MSDN获得了以下代码。基本上,我想创建一个应用程序(客户端),它不断地等待来自服务器的命令来完成某项任务。由于服务器无法直接与客户端通信,因此客户端必须打开与服务器的连接,在服务器无限期地保持请求打开时请求某些内容,直到它使用该命令响应客户端。 reader.ReadLineAsync()将阻止执行,直到服务器响应。 reader.ReadLineAsync()是否有最大超时时间?或者有更好的方法吗?
try
{
//Create the StreamSocket and establish a connection to the echo server.
Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
//The server hostname that we will be establishing a connection to. We will be running the server and client locally,
//so we will use localhost as the hostname.
Windows.Networking.HostName serverHost = new Windows.Networking.HostName("localhost");
//Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc.
//For the echo server/client application we will use a random port 1337.
string serverPort = "1337";
await socket.ConnectAsync(serverHost, serverPort);
//Write data to the echo server.
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
string request = "test";
await writer.WriteLineAsync(request);
await writer.FlushAsync();
//Read data from the echo server.
Stream streamIn = socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = await reader.ReadLineAsync();
}
catch (Exception e)
{
//Handle exception here.
}