Search code examples
javasocketsasyncsocket

Java - async socket channel cannot connect to remote async server socket channel


I created and debugged a simple net application that uses AsynchronousSocketChannel and AsynchronousServerSocketChannel and they work fine when accessed via localhost, but even if I move the server application to another device it refuses to connect at all. I first noticed this when I tried to port-forward the application, but upon moving it onto a device on the same network and connecting via the IPv4 it still didn't work. I checked both devices and they both are allowing Java through the firewall and there is nothing blocking the port number I am using (I have also tested various other ports). The client can't even connect to the server if it's on the same machine and you use that machine's IPv4. It literally only works on localhost. Has anyone else ever had this issue?

This is how the server channel is opened:

serverSocket = AsynchronousServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress("127.0.0.1", port));

Solution

  • Fixed it by removing the IP part of the InetSocketAddress:

    serverSocket = AsynchronousServerSocketChannel.open();
    serverSocket.bind(new InetSocketAddress(port));
    

    Replacing 127.0.0.1 with the IPv4 of the machine has the same effect. If someone could explain this that would be great, because every example I've seen online has binded to localhost. Are AsynchronousServerSocketChannels not supposed to be accessed remotely or something?