Chat room high frequency, low latency fully meet the characteristics of websocket, so chat room use websocket again fit.
Chat room function is not much more than the previous section of code, mainly in the handshake phase of the user's session to do processing, the user's message distribution and processing.
Handshake phase handshakeinterceptor needs to be handled
Public classHandshakeinterceptorextendshttpsessionhandshakeinterceptor {.... @Override Public BooleanBeforehandshake (serverhttprequest request, serverhttpresponse response, Websockethandler Wshandler, Map<String, Object>attributes)throwsException {System.out.println ("Before handshake"); if(Requestinstanceofservletserverhttprequest) {servletserverhttprequest ServletRequest=(servletserverhttprequest) request; HttpSession Session= Servletrequest.getservletrequest (). GetSession (false); String username= (String) session.getattribute ("username"); if(Username! =NULL&& ". Equals (" ")) Attributes.put ("Username", username); } return Super. Beforehandshake (Request, response, Wshandler, attributes); }
MessageHandler the message needs to be distributed
Public classMessageHandlerextendsTextwebsockethandler {//Save user's WebSocket connectionPrivatemap<string,websocketsession> users =NewHashmap<string,websocketsession>(); protected voidHandletextmessage (websocketsession session, TextMessage message)throwsException {if(!"". Equals (Message.getpayload ())) session.sendmessage (message); } Public voidAfterconnectionestablished (websocketsession session)throwsException {//After connection is established, save user information and send login information to all online usersUsers.put (Session.getid (), session); String username= (String) session.getattributes (). Get ("username"); if(Users! =NULL){ for(Websocketsession wssession:users.values ()) {handlemessage (wssession,NewTextMessage (username + "joined!!")); } }} @Override Public voidAfterconnectionclosed (websocketsession session, Closestatus status)throwsException {//exit, need to remove user informationUsers.remove (Session.getid ()); String username= (String) session.getattributes (). Get ("username"); if(Users! =NULL){ for(Websocketsession wssession:users.values ()) {handlemessage (wssession,NewTextMessage (username + "left!!")); }}}//mass information Public voidSendmsgtousers (TextMessage message)throwsexception{if(Users! =NULL){ for(Websocketsession wssession:users.values ()) {handlemessage (wssession, message); } } } }
The core code is handshakeinterceptor and MessageHandler, as follows:
Attached code: Http://git.oschina.net/yongjian1992/websocket
Learn WebSocket (ii): Use spring WebSocket to make a simple chat room