Question

I am making a chat in Java which uses a TCP protocol. I have a client and a server side.

To send a message to another user, I have to send the message to the server through my client, and the server has to send it to another client.

The server holds the addresses of both online users. When I send a private message, the server finds the ip and a port and creates a socket from them. The problem is that it doesn’t work correctly.

Here’s the code:

int portNumber = 4444;
String host = "192.168.0.100”;
Socket link;
try {
    link = new Socket(host, portNumber);
    // Then I set to already created PrintWriter the outputstream
    out = new PrintWriter(link.getOutputStream(), true);
} catch (Exception e) {}
// Unfortunately the server freezes here (it doesn't show anything).

How to solve this problem? Where dod I make a mistake? Thank you in advance.

Was it helpful?

Solution

You shouldn't create a new Socket to send a message. Instead, use a socket of an existing connection.

The sequence should be the following:

  1. Client A connects to the server (server stores the connection as SocketA).
  2. Client B connects to the server (server stores the connection as SocketB).
  3. Server reads a private message from SocketA. The message is addressed to client B.
  4. Server finds the existing socket for client B. It's SocketB.
  5. Server sends the message into SocketB.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top