TCP socket error 10061

社会主义新天地 提交于 2019-12-25 07:49:02

问题


I have created a windows service socket programme to lisen on specific port and accept the client request. It works fine.

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();

    }

But I need the service programme to listen on multiple port and accept the client request on any available port.

So I enhanced the application to bind to port 0(zero), so that it can accept the request on any available port.

But then I got the error 10061

No connection could be made because the target machine actively refused it.

I am unable to know whats the reason of getting this error.

Can anybody please suggest the way to enhance the code to accept the request on any port.

But the client need to send request to connect to specific port. e.g client1 should connect to port 8030, client2 should connect to port 8031.


回答1:


So I enhanced the application to bind to port 0(zero), so that it can accept the request on any available port.

Wrong. 0 means that the OS should assign a port. A server can only listen at one port at a time. The listen socket just accepts new connections.

The new connection will have the same local port, but the combination of Source (ip/port) and destination (ip/port) in the IP header is used to identify the connection. That's why the same listen socket can accept multiple clients.

UDP got support for broadcasts if that's what you are looking for.

Update:

A very simplified example

  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

Simply keep calling Accept for each client you want to accept. I usually use the asynchronous methods (Begin/EndXXX) to avoid blocking.



来源:https://stackoverflow.com/questions/9077606/tcp-socket-error-10061

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!