c# - TCP 套接字错误 10061

标签 c# tcp serversocket

我创建了一个 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/

相关文章:

c# - 在邮件中附加 excel 后检索空白 Excel

c# - TextBlock.Text 更新 ViewModel 和 CodeBehind WPF

c# - 在 TCP 中接收数据

java - Python Server/Java客户端“连接被拒绝:连接”

java - 支持多种类型操作的客户端套接字和服务器套接字之间通信的最佳方式是什么?

c# - 在 .NET XSLT 中使用 document() 函数会产生错误

c# - 如何进行惰性注入(inject)的异步初始化

http - 使用 std 在 Rust 中发出 HTTP 请求

networking - 为什么TCP在接收方缓冲数据

java - Socket 程序中的错误,发送空白消息并且每条消息之前都有一些奇怪的符号