Jaden Wang
Jaden Wang

Reputation: 108

How to use data from Client Handler Threads in Java

I followed a few tutorials and found out how to use threads for multithreading socket servers. I've created a Server class that has ClientServiceThread class for clients. When the thread receives a message from the client, how can I access that information using the Server class?

Here is my Server Thread:

public void run(){
        game = new Game();
        try{
            serverSocket = new ServerSocket(port);
            System.out.println("Server Started");
        }
        catch (IOException e){
            System.out.println(e);
        }

        while(true) {
            try {
                Socket clientSocket = serverSocket.accept();
                ClientServiceThread cliThread = new ClientServiceThread(clientSocket);
                threads.add(cliThread);
                cliThread.start();
            } catch(IOException e) {
                e.printStackTrace();

            }
        }


    }

Here is my ClientServiceThread class:

public void run() {
        boolean m_bRunThread = true;
        System.out.println("Accepted Client Address - " + socket.getInetAddress().getHostAddress());
        try {
            out = new ObjectOutputStream(socket.getOutputStream());
            in = new ObjectInputStream(socket.getInputStream());

            while(m_bRunThread) {
                String clientCommand = in.readUTF();
                System.out.println("Client Says :" + clientCommand);

                if(!gameStarted) {
                    out.writeUTF("GAME_ALREADY_STARTED");
                    out.flush();
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

EDIT 1: Essentially, I'm listening to commands/messages on the client handler threads. I later want to process them into my Server so I can manipulate my Game object through it.

Upvotes: 0

Views: 2099

Answers (1)

Alejandro C.
Alejandro C.

Reputation: 3801

The approach I'd recommend is to pass the game object to the client threads (it has to be thread-safe!), and then let the client threads take the actions on the game object directly. This will simplify your server class, and give you a single place to handle incoming messages.

Upvotes: 0

Related Questions