Search code examples
c#tcpserversocket

TCP socket error 10061


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.


Solution

  • 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.