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