Search code examples
javasocketsclient-servernetwork-connection

How can I connect a client to a server in Java using Socket


I am trying to write a client-server app that connects a PC as a client to my PC as a server. When I enter 127.0.0.1 as server IP in client side, in my PC, it works properly so it's not a coding problem. Also when I enter my IP (got it from nslookup command in kali) and connect to internet, client connects to server properly.

But when I open my client app in other PC and server app in my PC, the client side a "Connection Time out" Exception will be thrown.

I have tried turning off the firewall in the client side (Windows 10) but not from the server side.

Here are my codes:

Server:

ServerSocket server = new ServerSocket(SERVER_PORT);

Socket client = server.accept();

//Some codes

Client:

Socket server = new Socket(SERVER_IP, SERVER_PORT);

Solution

  • For better answer we need more informations from you. But from this what you post, this is best answer i can make. You didn't explain what is your goal, do you want to make connection inside local network or you would like to make connection to 'outside world', over internet.

    If you like to make two PCs communicate inside local network, than you must make sure they are on same network, or more accurate, that they are connected to same router. You have to set your server IP address to IP address on your local network, that would probably be something like 192.168.xxx.xxx

    If you want to communicate over internet, i suggest test in local network first, as described before. If it works on local network, then you have to deal with firewalls, router setting,etc to make it work on the internet too.

    Take look at this too Use Socket-communication over different networks