对于异步 TCP 侦听器,此模式是否正确?
我想知道我正在构建的应用程序是否做得正确。应用程序必须接收传入的 TCP 连接,并为每个调用使用一个线程,以便服务器可以并行应答多个调用。
我正在做的就是在获得接受的客户端后立即再次调用 BeginAcceptTcpClient
。我猜当 ConnectionAccepted
方法被调用时,它实际上是在一个单独的线程中。
public class ServerExample:IDisposable
{
TcpListener _listener;
public ServerExample()
{
_listener = new TcpListener(IPAddress.Any, 10034);
_listener.Start();
_listener.BeginAcceptTcpClient(ConnectionAccepted,null);
}
private void ConnectionAccepted(IAsyncResult ia)
{
_listener.BeginAcceptTcpClient(ConnectionAccepted, null);
try
{
TcpClient client = _listener.EndAcceptTcpClient(ia);
// work with your client
// when this method ends, the poolthread is returned
// to the pool.
}
catch (Exception ex)
{
// handle or rethrow the exception
}
}
public void Dispose()
{
_listener.Stop();
}
}
我做得对吗?
干杯。
I was wondering if I'm doing right in an application I'm building. The app has to receive incoming TCP connections, and use a thread per call, so the server can answer multiple calls in parallel.
What I'm doing is call BeginAcceptTcpClient
again as soon I got an accepted client. I guess that when the ConnectionAccepted
method is hit, it's actually in a separate thread.
public class ServerExample:IDisposable
{
TcpListener _listener;
public ServerExample()
{
_listener = new TcpListener(IPAddress.Any, 10034);
_listener.Start();
_listener.BeginAcceptTcpClient(ConnectionAccepted,null);
}
private void ConnectionAccepted(IAsyncResult ia)
{
_listener.BeginAcceptTcpClient(ConnectionAccepted, null);
try
{
TcpClient client = _listener.EndAcceptTcpClient(ia);
// work with your client
// when this method ends, the poolthread is returned
// to the pool.
}
catch (Exception ex)
{
// handle or rethrow the exception
}
}
public void Dispose()
{
_listener.Stop();
}
}
Am I doing right?
Cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,您可以像这样使方法静态:
也许您不希望它是静态的,但这样您就可以将方法移动到您喜欢的位置,并且不依赖于此类中的成员变量,而是依赖于另一个类中的成员变量。
IE:解耦服务器tcp逻辑和服务器客户端逻辑。
Well you could make the method static like this :
maybe you don't want it to be static but this way you could move the method where you like it and do not depend on member variables in this class but another one.
I.E: decouple server tcp logic and server client logic.