0

Suppose we have chat application which allows us to have contacts and we can chat to anyone from our contacts. Our application should behave like server when receiving messages and client when sending messages. In Java when we want to make a TCP connection client, we use sockets as:

Socket client = new Socket(hostIPAddress, portNumber);

Now, I have learnt using sockets using my local machine as a server, but for a chat application to be practical it should allow communication b/w two different devices.

Now, the client must have the IP address of the other device we want to communicate to. Should I maintain a list of IP addresses of all the contacts in chat application. Also, IP addresses may be dynamic and may change time to time. How can such problem be tackled? Intuitively, it seems that IP addresses won't work.

Edit:

The aim is to setup peer to peer connection rather than using centralized servers. I want to make a simple application with not much complications.

Navjot Singh
  • 678
  • 7
  • 18
  • You need to keep a broker or Messaging queue (Like MQTT) in one of the machine where people connect and talk to each other. – Saif Ahmad Dec 10 '18 at 11:50
  • In that case, sockets have no use. @SaifAhmad – Navjot Singh Dec 10 '18 at 12:02
  • Socket is only use full when you need to have one to one connection. It's very difficult to maintain one to many. – Saif Ahmad Dec 10 '18 at 12:04
  • I think you first need to get clear about terminology. The essence of a server isn't to use a socket. It is that you have a continuously running program, that uses a ServerSocket and that clients talk to all the time. That is the first question here: do you want a pure peer to peer network, or do you want an architecture where all clients ONLY talk to centralized servers?! There is a big difference between these two things! – GhostCat Dec 10 '18 at 12:13
  • Yes I want a peer to peer network....that is why i want to use sockets...I know apps like whatsapp use centralized servers and i don't want to complicate things that much. – Navjot Singh Dec 10 '18 at 12:25

1 Answers1

1

You will need to use a technology called WebSockets. It is built precisely for the use case you have at the moment. See https://www.baeldung.com/java-websockets for more information.

fpezzini
  • 774
  • 1
  • 8
  • 17