简体   繁体   中英

How server can send message to client in Java

Response is returned by the server when Request is sent. This is normal request-response mechanism but problem is-- Sometimes server needs to send some notification back to client.

I implemented this using Keep-Alive requests, That is Server queues messages to be sent and sends as a response whenever ALIVE request comes. But this creates bottleneck at the server, and server could not detect if connection is closed.

I believe there is a way to handle this. I attempted, but failed since .readObject on ObjectOutputStream cant work concurrently.

Client opens connection to server and creates following streams for communicate.

ObjectOutputStream obos;
ObjectInputStream obis;
public Response send(Request req){
    Response resp=null;
    try {
        obos.writeObject(req); //request from Client
        resp=( Response )obis.readObject(); //Reply from server
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
    return resp;
}

public void run(){
    asyncReceive();
}

void asyncReceive(){    //notifications from server
    try {
        Message m=(Message)obis.readObject();
    } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
    }
}

You might be able to use two different threads that handle receiving and sending.

The sending thread could be using a thread safe queue of messages to send, so it just blocks whenever the queue is empty. You could add messages to the queue periodically in a timer task thread for notifications, or as a response to a client request.

I think readObject() should throw if the socket is closed in the meantime.

what you need is a messaging system with a messaging broker, something like RabbitMQ or ActiveMQ the clients need to register to a topic that is created by the server. when the the server pushes a message, it is the job of the broker to notify the clients of it

Consider making your client listen on a socket as well.

When your client sends its first request to the server it includes in the request the port and IP address it is listening on. The server then establishes a connection with the client on that address and port. The server can then send a request to the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM