jjenkov / java-nio-server

A Java NIO Server using non-blocking IO all the way through.
Apache License 2.0
923 stars 461 forks source link

can this server push message to client ? #4

Open PudgeMa opened 7 years ago

PudgeMa commented 7 years ago

I want to make a Tcp Server that can push message to client, and I'm worry about how to save and mark every SocketChannel of client. does your code have this function ? thanks.

jjenkov commented 7 years ago

Hi,

I am not sure if this design has that ability already, but I have made a more advanced version of a TCP server which can do that - based on exactly the same design. It is definitely possible to add.

The extended design assigns a socket ID to each socket, and inserts them into a Map. Then each socket can be identified via that id (just an incrementing long). Also, the messages that are read from a socket contains a reference to the socket (or socket ID) of the socket they came from, so a reply can be sent back to the correct socket.

On Sun, Jul 23, 2017 at 11:53 AM, mmmmar notifications@github.com wrote:

I want to make a Tcp Server that can push message to client, and I'm worry about how to save and mark every SocketChannel of client. does your code have this function ? thanks.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/jjenkov/java-nio-server/issues/4, or mute the thread https://github.com/notifications/unsubscribe-auth/ADb7WaTagmqWiBloOJC7mEHCc1dBowy2ks5sQxgTgaJpZM4OgaMr .

-- Jakob Jenkov jakob@jenkov.com Founder, CEO

Jenkov Aps http://jenkov.com http://tutorials.jenkov.com

http://feeds2.feedburner.com/jenkov-com

PudgeMa commented 7 years ago

@jjenkov yeah. I have the same idea. I think it may be difficult to remove socket from the map when the socket disconnects with server, so the heartbeat may be need to detect that.

jjenkov commented 7 years ago

Actually, this server already assigns an ID to the sockets and puts them into a Map. It also removes them again when the sockets are closed. Look at this code from the SocketProcessor:

    if(socket.endOfStreamReached){
        System.out.println("Socket closed: " + socket.socketId);
        this.socketMap.remove(socket.socketId);
        key.attach(null);
        key.cancel();
        key.channel().close();
    }