java chat sending users list from server to client

2019-08-26 03:22发布

I write client-server chat using sockets. Help me please understand how send the list of current registered users from server to clients and update it when list changed. I read this similar post but steel don't understand how to do it. I used BufferedReader and PrintWriter streams for sending and receiving messages. And I don't want sending the list of the users any time when clients send messages.

I keep list of users in a map as a key set on the server side.

public class Server{
    private final Map<String, ServerThread> clients = Collections.synchronizedMap(new TreeMap<>());
    //.....
}

I read on one forum, if use serialization, than all serializable classes have to be both the sending and the receiving side. But I don't need server class on client side.

UPDATE: If I will use ObjectOutputStream / ObjectInputStream instead BufferedReader and PrintWriter whether the following approach is useful for distinguishing messages from the list of user names?

//code on client side:
Object received = input.readObject();
if (received instanceof List) {
    List<String> users = (List) received;
    //display users in JList
} else if (received instanceof String) {
    String message = (String) received;
    //display in JTextArea
}

0条回答
登录 后发表回答