Answer the question
In order to leave comments, you need to log in
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();
}
}
}
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 чата
*/
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question