[我仅限于Visual Studio 2010,因此,C#4。异步和等待对我不可用。]
我正在为我的一个项目开发网络架构,该项目通过服务器和客户端之间的网络发送数据包,但是客户端和服务器必须在等待时继续运行,因此代码必须是非阻塞的,因此我想使用异步方法。但是,除了简单的同步一次性IO之外,我对执行的操作知之甚少,尤其是在使用NetworkStream时。我正在尝试做的是:
1)客户端连接到服务器
2)服务器接受连接
3)服务器等待来自客户端的数据
4)服务器处理数据
5)服务器响应客户端
6)打开连接时,请从3开始重复。
我想使用NetworkStream包装套接字。但是我是异步I/O的新手,我不确定在等待响应时,特别是在使用NetworkStream时,如何在不阻止服务器/客户端代码其他部分的情况下执行此操作。在我的研究中,我看到了使用类似以下内容的示例:
while(true){
socket.BeginAccept(new AsyncCallback(AcceptCallback), socket );
}
但是似乎该循环仍会阻止应用程序。谁能给我一些关于如何做到这一点的指示(公顷)?我无法找到许多使连接保持打开状态的示例,只有“客户端连接”->“客户端发送”->“服务器接收”->“服务器发送”->“断开连接”。我不是要完整的代码,而只是要求提供一些摘要。
最佳答案
这是将async/await与NetworkStream
一起使用的非常简单的示例:
SocketServer.cs:
class SocketServer
{
private readonly Socket _listen;
public SocketServer(int port)
{
IPEndPoint listenEndPoint = new IPEndPoint(IPAddress.Loopback, port);
_listen = new Socket(SocketType.Stream, ProtocolType.Tcp);
_listen.Bind(listenEndPoint);
_listen.Listen(1);
_listen.BeginAccept(_Accept, null);
}
public void Stop()
{
_listen.Close();
}
private async void _Accept(IAsyncResult result)
{
try
{
using (Socket client = _listen.EndAccept(result))
using (NetworkStream stream = new NetworkStream(client))
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
Console.WriteLine("SERVER: accepted new client");
string text;
while ((text = await reader.ReadLineAsync()) != null)
{
Console.WriteLine("SERVER: received \"" + text + "\"");
writer.WriteLine(text);
writer.Flush();
}
}
Console.WriteLine("SERVER: end-of-stream");
// Don't accept a new client until the previous one is done
_listen.BeginAccept(_Accept, null);
}
catch (ObjectDisposedException)
{
Console.WriteLine("SERVER: server was closed");
}
catch (SocketException e)
{
Console.WriteLine("SERVER: Exception: " + e);
}
}
}
Program.cs:
class Program
{
private const int _kport = 54321;
static void Main(string[] args)
{
SocketServer server = new SocketServer(_kport);
Socket remote = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Loopback, _kport);
remote.Connect(remoteEndPoint);
using (NetworkStream stream = new NetworkStream(remote))
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
Task receiveTask = _Receive(reader);
string text;
Console.WriteLine("CLIENT: connected. Enter text to send...");
while ((text = Console.ReadLine()) != "")
{
writer.WriteLine(text);
writer.Flush();
}
remote.Shutdown(SocketShutdown.Send);
receiveTask.Wait();
}
server.Stop();
}
private static async Task _Receive(StreamReader reader)
{
string receiveText;
while ((receiveText = await reader.ReadLineAsync()) != null)
{
Console.WriteLine("CLIENT: received \"" + receiveText + "\"");
}
Console.WriteLine("CLIENT: end-of-stream");
}
}
这是一个非常简单的示例,在同一过程中同时托管服务器和客户端,并且一次仅接受一个连接。它实际上只是出于说明目的。现实世界中的场景无疑将包括其他满足其需求的功能。
在这里,我将
NetworkStream
包裹在StreamReader
和StreamWriter
中。请注意,您必须调用Flush()
以确保实际发送了数据。为了更好地控制I/O,您当然可以直接使用NetworkStream
。只需使用Stream.ReadAsync()
方法而不是StreamReader.ReadLineAsync()
即可。还要注意,在我的示例中,编写是同步的。如果愿意,您也可以使用与阅读所示相同的基本技术来使此异步。编辑:
OP表示他们无法使用
async
/await
。这是使用NetworkStream
和旧式Begin/EndXXX()
API的客户端版本(当然会对服务器进行类似的更改):using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TestOldSchoolNetworkStream
{
class Program
{
private const int _kport = 54321;
static void Main(string[] args)
{
SocketServer server = new SocketServer(_kport);
Socket remote = new Socket(SocketType.Stream, ProtocolType.Tcp);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Loopback, _kport);
remote.Connect(remoteEndPoint);
using (NetworkStream stream = new NetworkStream(remote))
{
// For convenience, These variables are local and captured by the
// anonymous method callback. A less-primitive implementation would
// encapsulate the client state in a separate class, where these objects
// would be kept. The instance of this object would be then passed to the
// completion callback, or the receive method itself would contain the
// completion callback itself.
ManualResetEvent receiveMonitor = new ManualResetEvent(false);
byte[] rgbReceive = new byte[8192];
char[] rgch = new char[Encoding.UTF8.GetMaxCharCount(rgbReceive.Length)];
Decoder decoder = Encoding.UTF8.GetDecoder();
StringBuilder receiveBuffer = new StringBuilder();
stream.BeginRead(rgbReceive, 0, rgbReceive.Length, result =>
{
_Receive(stream, rgbReceive, rgch, decoder, receiveBuffer, receiveMonitor, result);
}, null);
string text;
Console.WriteLine("CLIENT: connected. Enter text to send...");
while ((text = Console.ReadLine()) != "")
{
byte[] rgbSend = Encoding.UTF8.GetBytes(text + Environment.NewLine);
remote.BeginSend(rgbSend, 0, rgbSend.Length, SocketFlags.None, _Send, Tuple.Create(remote, rgbSend.Length));
}
remote.Shutdown(SocketShutdown.Send);
receiveMonitor.WaitOne();
}
server.Stop();
}
private static void _Receive(NetworkStream stream, byte[] rgb, char[] rgch, Decoder decoder, StringBuilder receiveBuffer, EventWaitHandle monitor, IAsyncResult result)
{
try
{
int byteCount = stream.EndRead(result);
string fullLine = null;
if (byteCount > 0)
{
int charCount = decoder.GetChars(rgb, 0, byteCount, rgch, 0);
receiveBuffer.Append(rgch, 0, charCount);
int newLineIndex = IndexOf(receiveBuffer, Environment.NewLine);
if (newLineIndex >= 0)
{
fullLine = receiveBuffer.ToString(0, newLineIndex);
receiveBuffer.Remove(0, newLineIndex + Environment.NewLine.Length);
}
stream.BeginRead(rgb, 0, rgb.Length, result1 =>
{
_Receive(stream, rgb, rgch, decoder, receiveBuffer, monitor, result1);
}, null);
}
else
{
Console.WriteLine("CLIENT: end-of-stream");
fullLine = receiveBuffer.ToString();
monitor.Set();
}
if (!string.IsNullOrEmpty(fullLine))
{
Console.WriteLine("CLIENT: received \"" + fullLine + "\"");
}
}
catch (IOException e)
{
Console.WriteLine("CLIENT: Exception: " + e);
}
}
private static int IndexOf(StringBuilder sb, string text)
{
for (int i = 0; i < sb.Length - text.Length + 1; i++)
{
bool match = true;
for (int j = 0; j < text.Length; j++)
{
if (sb[i + j] != text[j])
{
match = false;
break;
}
}
if (match)
{
return i;
}
}
return -1;
}
private static void _Send(IAsyncResult result)
{
try
{
Tuple<Socket, int> state = (Tuple<Socket, int>)result.AsyncState;
int actualLength = state.Item1.EndSend(result);
if (state.Item2 != actualLength)
{
// Should never happen...the async operation should not complete until
// the full buffer has been successfully sent,
Console.WriteLine("CLIENT: send completed with only partial success");
}
}
catch (IOException e)
{
Console.WriteLine("CLIENT: Exception: " + e);
}
}
}
}
请注意,即使遗漏了一堆异常处理逻辑,该代码也相当长,至少部分原因是
TextReader
没有内置的异步API,因此对输入数据的处理是这里更加冗长。当然,这是针对简单的基于行的文本交换协议(protocol)。就数据拆包方面而言,其他协议(protocol)可能或多或少复杂,但是NetworkStream
的底层读取和写入元素将是相同的。关于c# - C#中的套接字,我如何通过NetworkStream异步读取和写入数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26917176/