Search code examples
javanetwork-programmingtcpclienttcpserver

Peer to peer communication over internet implementation in java


I am trying to build a system in java, where one computer acts as the server and the other one as the client and connect them together (i.e send data b/w them) on the public network. Here is my pseudo code -

Server.java

ServerSocket server = new ServerSocket(55955);
Socket socket = server.accept();

Client.java

 Socket socket = new Socket("<ip address of server>", 55955);
//code to send and receive response from server

The code works fine if I have my server and client running on my computer.But if i run the server on a different machine (a friend's pc on the internet) and try to use that ip on the client running my machine, its not working. I did a lot of googling and did not find a appropriate solution other than opening up the firewall or ports on the machine.

  1. Is there any other option to connect b/w the computers on the internet without any forwarding or opening the ports ?
  2. There are a few peer to peer systems (eg: skype)etc that does the same thing I am trying to achieve (and in my best of my knowledge its without opening any ports on the host machine). Please correct me if I am wrong.

Thank you.


Solution

  • Thank you. I am adding the solution which I was finally able to work with.

    This can be achieved using NAT Hole punching. Found these awesome articles which explains the approach.

    1. Peer-to-Peer Communication Across Network Address Translators
    2. How Skype gets around firewalls