R
R
Rostislav2016-04-21 11:57:07
Java
Rostislav, 2016-04-21 11:57:07

How to send a message to all clients connected to the server?

I'm trying to write a chat with a client-server architecture. The server is based on Java Sockets. Android client.
I created a Message class that implements the Serializable interface. Actually, the client and the server exchange objects of this class.
I managed to do authorization and registration. The problem arose in the following: the client sends a message that should get into the group chat. That is, the server must, after accepting this message, send it to all online clients so that they display it on their own. And this is the message I can't send.
Did the following:

/*
 socketList - static LinkedList<Socket>
 globalMessage- объект сериализуемого класса Message
 client - Socket объект клиента от которого приходит сообщение
*/


for (Socket socket : RServer.socketList) {
    if (!socket.equals(client) & !socket.isClosed()) {
        try {
            ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
            os.flush();
            os.writeObject(globalMessage);
            os.close();
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
    }


}

On the client in a background such function turns.
public void listenServerMessages() {
    try {
        while (true) {
            Message message = (Message) objectInputStream.readObject();
            if (message.getType() == Message.MESSAGE & !message.isErr()) {
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setDate(DateFormat.getDateTimeInstance().format(new Date()));
                chatMessage.setMe(false);
                chatMessage.setMessage(message.getMessage());
                displayMessage(chatMessage);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    /*
    ChatMessage - класс сообщения в главной View чата
    
    */
}

Perhaps this approach is wrong, because the server itself should not send something without a request. That's why I'll ask the following question at the same time - maybe it's better to make a table in the database, and save all correspondence there, and on the client make a request to the server in the background so that the latter returns new messages? If so, with what period should such requests be made?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kosarev, 2016-04-21
Makkall @viogull

In general, the approach is normal, but you need to manually manage connections. To simplify this task, you can use Netty. On the client side, it is desirable to add Thread.sleep(1) in the while(true) block, this will add a thread suspension for 1 ms, but will seriously reduce the load on the CPU.
A request to receive new messages can also be implemented. This is how it is done, as far as I know, in Telegram clients.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question