c#套接字处理多个客户端 [英] c# sockets handling multiple clients
问题描述
我有以下代码,我想将其实现为我的服务器.据我了解,它是异步的.并且应该允许来自多个客户端的连接...
I have the following code which I want to implement as my server. As I understand it is async. and should allow connections from multiple clients...
public void Start()
{
TcpListener listener = new TcpListener(IPAddress.Any, 10250);
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
IAsyncResult res = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
connectionWaitHandle.WaitOne();
}
}
private void HandleAsyncConnection(IAsyncResult res)
{
TcpListener listener = (TcpListener)res.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(res);
connectionWaitHandle.Set();
StringBuilder sb = new StringBuilder();
var data = new byte[client.ReceiveBufferSize];
using (NetworkStream ns = client.GetStream())
{
// Test reply
Byte[] replyData = System.Text.Encoding.ASCII.GetBytes(DateTime.Now.ToString());
ns.Write(replyData, 0, replyData.Length);
ns.Flush();
ns.Close();
}
client.Close();
}
我有一个测试应用程序,它只是向我的服务器发出请求.正如您在代码中看到的,服务器只回复其日期/时间.测试应用程序发送 20 个请求,这些请求只是测试字符串.对于这些请求中的每一个,它都会打开一个套接字,将数据发送到我的服务器,然后再次关闭套接字.
I have a test app which simply fires requests to my server. As you can see in the code the server just replies with its date/time. The test app sends say 20 requests which are simply test strings. For each of these requests it opens a socket, sends the data to my server and then closes the socket again.
这适用于运行一个测试应用程序.但是,如果我打开两个测试应用程序,第二个应用程序无法连接到服务器.我想是因为我正在处理异步请求.并且因为我的测试应用程序在每次调用之前打开然后关闭套接字,所以我可以处理来自多个客户端的请求?
This works fine with one test app running. However, if I open two test apps the second one cannot connect to the server. I thought because I am handling the request async. and because my test app opens then closes the socket before each call I could handle requests from multiple clients?
推荐答案
编辑
如果使用>=.Net4.5,最好使用允许采用async
和await
的新网络方法.因此,最好遵循我在 这篇文章 作为起点.
Edit
If using >=.Net4.5, it's better to use the new network methods that then permit the adoption of async
and await
. As such, it might be better to follow the example I provided in this post as a starting point.
以下代码演示了如何在不为每个连接分离新线程的情况下异步接受多个客户端.
The following code demonstrates how to accept multiple clients asynchronously without spinning off a new thread per connection.
private TcpListener listener;
public void Start()
{
listener = new TcpListener(IPAddress.Any, 10250);
listener.Start();
Console.WriteLine("Listening...");
StartAccept();
}
private void StartAccept()
{
listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);
}
private void HandleAsyncConnection(IAsyncResult res)
{
StartAccept(); //listen for new connections again
TcpClient client = listener.EndAcceptTcpClient(res);
//proceed
}
您可以将此模式用于大多数异步操作.
You can use this pattern for most async operations.
这篇关于c#套接字处理多个客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!