我创建了一个 Windows 服务套接字程序来监听特定端口并接受客户端请求。它工作正常。
protected override void OnStart(string[] args)
{
//Lisetns only on port 8030
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 8030);
//Defines the kind of socket we want :TCP
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Bind the socket to the local end point(associate the socket to localendpoint)
serverSocket.Bind(ipEndPoint);
//listen for incoming connection attempt
// Start listening, only allow 10 connection to queue at the same time
serverSocket.Listen(10);
Socket handler = serverSocket.Accept();
}
但我需要服务程序监听多个端口并在任何可用端口上接受客户端请求。
所以我增强了应用程序以绑定(bind)到端口 0(零),以便它可以接受任何可用端口上的请求。
但是我得到了错误10061
No connection could be made because the target machine actively refused it.
我无法知道出现此错误的原因。
任何人都可以建议增强代码以在任何端口上接受请求的方法。
但是客户端需要发送请求连接到特定的端口。例如,client1 应该连接到 port 8030
,client2 应该连接到 port 8031
。
最佳答案
So I enhanced the application to bind to port 0(zero), so that it can accept the request on any available port.
错了。 0 表示操作系统应该分配一个端口。服务器一次只能监听一个端口。监听套接字只接受新连接。
新连接将具有相同的本地端口,但使用 IP header 中源(ip/端口)和目标(ip/端口)的组合识别连接。这就是同一个监听套接字可以接受多个客户端的原因。
UDP 获得了对广播的支持,如果您正在寻找的话。
更新:
一个非常简单的例子
Socket client1 = serverSocket.Accept(); // blocks until one connects
Socket client2 = serverSocket.Accept(); // same here
var buffer = Encoding.ASCII.GetBytes("HEllo world!");
client1.Send(buffer, 0, buffer.Count); //sending to client 1
client2.Send(buffer, 0, buffer.Count); //sending to client 2
只需为您要接受的每个客户继续调用 Accept
。我通常使用异步方法 (Begin/EndXXX) 来避免阻塞。
关于c# - TCP 套接字错误 10061,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9077606/