Closed better-github-hub closed 9 months ago
For example this Session : public void onOpen(Session session,@PathParam("userId") String userId) ;
I want to get the Session when a client to connect webSocketServer . please help me, thank you very much.
I don't think Java provides a built in way to parse URL query parameters. You can get the full query string by doing URI.create(handshake.getResourceDescriptor()).getQuery()
But for splitting and decoding it, you either need a library or just search for code online
I just want to get the unique identification of a connection of websocket . How can I get the unique identification ?
Web sockets don't really have a unique connection ID, you can either use the WebSocket object itself or generate a random ID in the onOpen function and store it in the WebSocket with the setAttachment method.
the "Sec-WebSocket-Key" in the headers , Can does as a unique connection ID ?
as follows:
@Override public void onOpen(WebSocket conn, ClientHandshake handshake) { String webSocketKey = handshake.getFieldValue("Sec-WebSocket-Key"); cache.set(webSocketKey,conn); conn.send("Welcome to the server!"); //This method sends a message to the new client broadcast( "new connection: " + handshake.getResourceDescriptor() ); //This method sends a message to all clients connected System.out.println("new connection to " + conn.getRemoteSocketAddress()); }
Thank you . setAttachment method can store any values of I want ?
Yes, setAttachment and getAttachment can be used for anything you want.
But keep in mind that Sec-WebSocket-Key is generated by the client, and a malicious client could send multiple connections with the same Sec-WebSocket-Key. So you can't rely on it being unique.
That's very good . I get what I want to . setAttachment is enough . Thank you .
as follows :
@Override public void onOpen(WebSocket conn, ClientHandshake handshake) { SocketSession session=new SocketSession(); session.setId(ID.nextId()); session.setSessionMap(new HashMap<>()); conn.setAttachment(session); this.cache.set(SESSION_PREFIX +session.getId(),session); conn.send("Welcome to the server!"); //This method sends a message to the new client broadcast( "new connection: " + handshake.getResourceDescriptor() ); //This method sends a message to all clients connected System.out.println("new connection to " + conn.getRemoteSocketAddress()); }
@Data public class SocketSession implements Serializable { private String id; private Map<String,Object> sessionMap; }
How to distinguish the uniqueness of each session of connect ?
@Override public void onOpen(WebSocket conn, ClientHandshake handshake) { conn.send("Welcome to the server!"); //This method sends a message to the new client broadcast( "new connection: " + handshake.getResourceDescriptor() ); //This method sends a message to all clients connected System.out.println("new connection to " + conn.getRemoteSocketAddress()); }