Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello. I want to create a Java server that will allow 2 or more sockets to communicate with each other. I tried this with the code shown below and the second client to connect can send to the first one, but the first to connect cannot send to the second client.

Code to accept two sockets:

MessageServer.java:
Java
package io.github.sirender125.Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;

public class MessageServer {
    private int port;
    private ServerSocket serverSocket;
    private LinkedList<ClientHandler> clientHandlers = new LinkedList<>();

    public MessageServer(int port) {
        this.port = port;
    }

    public void start() throws IOException {
        serverSocket = new ServerSocket(port);

        System.out.printf("Server started on port %d.", port);

        for (int i = 0; i < 2; i++) {
            Socket client = serverSocket.accept();
            System.out.println("A client connected.\n");

            ClientHandler ch = new ClientHandler(client, this);
            clientHandlers.add(ch);
            ch.start();
        }
    }

    //public void end() throws IOException {
    //    serverSocket.close();
    //}

    public long getClientCount() {
        return clientHandlers.size();
    }

    public void broadcast(String message, ClientHandler exclude) {
        for (ClientHandler ch : clientHandlers) {
            if (ch != exclude) {
                ch.sendMessage(message);
            }
        }
    }

    public void kickClient(ClientHandler client) {
        clientHandlers.remove(client);
        client.interrupt();
    }
}


ClientHandler.java:
Java
package io.github.sirender125.Server;

import java.io.*;
import java.net.*;

public class ClientHandler extends Thread {
    private Socket client;
    private BufferedReader reader;
    private PrintWriter writer;
    private MessageServer messageServer;

    public ClientHandler(Socket socket, MessageServer messageServer) throws IOException {
        this.client = socket;
        this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.writer = new PrintWriter(socket.getOutputStream(), true);
        this.messageServer = messageServer;
    }

    @Override
    public void run() {
        // Wait for at least one other client.
        while (messageServer.getClientCount() == 1) {

        }

        String line;

        // While the other clients have not disconnected.
        while (messageServer.getClientCount() > 1) {
            // Check for input.
            try {
                if ((line = reader.readLine()) != null) {
                    if (line.startsWith("message::")) {
                        // Send the message to all other clients.
                        messageServer.broadcast(line.substring(9), this);
                    }
                    else if (line.equals("exit")) {
                        // Kick the client and disconnect.
                        messageServer.kickClient(this);
                        client.close();
                    }
                }
            }
            catch (IOException ioe) {
                ioe.printStackTrace();
                try {
                    client.close();
                }
                catch (IOException ioe1) {
                    ioe1.printStackTrace();
                }
            }
        }
        try {
            client.close();
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public void sendMessage(String message) {
        writer.println("message::" + message);
    }

    public void kick() {
    
    }
}


Main.java:
Java
package io.github.sirender125.Server;

import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        if (args.length == 1) {
            int port = Integer.parseInt(args[0]);

            MessageServer messageServer = new MessageServer(port);

            try  {
                messageServer.start();
            }
            catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        else {
            System.err.println("Please pass valid arguments. (<port>)");
        }
    }
}



I'm sure that this code has a lot of problems and such. I am no pro. Please point them out and address any apparent reasons for the problem stated above.

Also, I am not sure whether I need to give you the client code, but I can if it would help. The problem seems server-related to me though.

What I have tried:

Rewriting the server code from scratch. (So it maybe the client's fault?)
Posted
Comments
Richard MacCutchan 23-Aug-21 3:52am    
Each time a client connects to the server the client functions need to be started in new thread. Each thread on the server then communicates independently with its client. Alternately you could use a queue mechanism to separate the messages of each client.
[no name] 23-Aug-21 17:56pm    
So a separate thread initiate each ClientHandler? I'm not sure I understand.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900