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.
这正常工作与一个测试应用程序的运行。不过,如果我开两个测试Apps中的第二个无法连接到服务器。我想因为我处理请求的异步。因为我的测试应用程序打开,然后在每次调用前关闭套接字我可以从多个客户端的处理请求?
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,最好使用新的网络中的方法然后允许通过的异步
和的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屋!