Garmaine Staff asked 4 months ago

I am writing a simple chat Java chat program. I have message objects, which are sent from clients through ObjectStreams. The message object are assumed to have the client source and destination addresses. The server is multi-threaded, with one thread handling client requests and a thread for each accepted connection.

I have no problem with the code involving a client sending a message object to a server and the server sending an acknowledgement message back to the same client. But I am having a lot of difficulty setting up the code for have a client, say client 1, sending an object to the server, and the server forwarding the output object stream to client 2's object input stream.

Here is the message object:

public Message(String name, String text, InetAddress source, InetAddress destination) { 
    this.name = name;
    this.text = text;
    this.destination = destination;
    this.source = source;}

Here is the server code snipped:

new Thread(() -> {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server started at " + new Date());

            while (true) {
                // listen for connection request
                Socket socket = serverSocket.accept();

                //System.out.println(socket);

                //System.out.println("Client " + socket.getInetAddress().getHostAddress());

                new Thread(() -> {
                    // read data from client
                    try (ObjectInputStream fromClient = new ObjectInputStream(socket.getInputStream());) {

                        while(true) {
                            // get message from client
                            Message message = (Message) fromClient.readObject();

I have tried saving the sockets or socket output streams in an array list, but I am not having any luck.

How can I complete the server so that it can forward client x's message object to client y?