Search code examples
javasocketsobjectinputstreamobjectoutputstream

Server doesn't receive more messages from client


I am creating a chat application. The client sends messages to the sever, the server just receives the first message but not more.

Server reading Thread

private void read(ObjectInputStream ois) {
    new Thread() {
        @Override
        public void run() {
            try {
                String[] contents = (String[]) ois.readObject();
                MainContainer.gh.add(new JLabel(contents[0] + " : " + contents[1]));
            } catch (Exception ex) {
                System.out.println("Sorry.");
            }
        }
    }.start();
}

Client write method

public void write(String[] contents) {
    try {
        oos.writeObject(contents);
    } catch (Exception ex) {
        System.out.println("Sorry");
    }
}

Thanks in advance. If you need extra code, you may request for that. Thanks.


Solution

  • Your code hasn't a loop.

    So it receive the first array named contents then exit.

    You should add a loop similar to this one

    while (true) {
        // Receive messages
    }