HTML5 WebSocket + Tomcat8 implementation ● real-time chat room for the Web version (single-user + multi-user)
I have previously created a websocket chat room for Tomcat 7, which is based on Tomcat 7 and jdk1.7. Some projects are under Tomcat 8 and there will be problems at this time, because it is not supported below 8, it implements websocket in the form of annotations. Refer to HTML5 WebSocket + Tomcat to implement Web instant chat rooms. The following describes how to implement chat rooms under 8, with multiple users adding single users!
The most important thing is to obtain the logon session of each user. Here the session is HttpSession, and websocket comes with the session, but in actual projects we may only use the first one, how can I get it under 8?
Here we need to write a class to inherit ServerEndpointConfig. Configurator:
package com.socket;import javax.websocket.HandshakeResponse;import javax.websocket.server.HandshakeRequest;import javax.websocket.server.ServerEndpointConfig;import javax.servlet.http.HttpSession;public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator { @Override public void modifyHandshake(ServerEndpointConfig config,HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); config.getUserProperties().put(HttpSession.class.getName(), httpSession); }}
Add this configuration in the websocket service, just like this
@ServerEndpoint(value = /websocket,configurator=GetHttpSessionConfigurator.class)
I put two httpsessions in a map and put them in as users enter, as shown below:
private static final Map
onlineUsers = new HashMap
();
The code is
Package com. socket; import java. io. IOException; import java. util. hashMap; import java. util. map; import javax. servlet. http. httpSession; import javax. websocket. endpointConfig; import javax. websocket. onClose; import javax. websocket. onError; import javax. websocket. onMessage; import javax. websocket. onOpen; import javax. websocket. session; import javax. websocket. server. serverEndpoint; import utils. messageUtil; @ ServerEndpoint (value =/websocket, aggregator = GetHttpSessionConfigurator. class) public class ChatServlet {private static final Map
OnlineUsers = new HashMap
(); Private static int onlineCount = 0; private HttpSession httpSession; private Session session; @ OnOpen public void onOpen (Session session, EndpointConfig config) {this. session = session; this. httpSession = (HttpSession) config. getUserProperties (). get (HttpSession. class. getName (); if (httpSession. getAttribute (user )! = Null) {onlineUsers. put (httpSession, this);} String names = getNames (); String content = MessageUtil. sendContent (MessageUtil. USER, names); broadcastAll (content); addOnlineCount (); // online shujia 1 System. out. println (a new connection is added! The number of online users is + onlineUsers. size () ;}@ OnClose public void onClose () {onlineUsers. remove (this); // Delete subOnlineCount () from the set; // The number of online operations minus 1 System. out. println (a connection is closed! The current number of online users is + getOnlineCount ();} @ OnMessage public void onMessage (String message, Session session) throws IOException {HashMap
MessageMap = MessageUtil. getMessage (message); // message processing class String fromName = messageMap. get (fromName); // The userId String toName = messageMap of the message. get (toName); // userId String mapContent = messageMap. get (content); if (toName. isEmpty () {sendOffLine (fromName, toName); return;} if (all. equals (toName) {String msgContentString = fromName +: + mapContent; // construct the sent message String content = MessageUtil. sendContent (MessageUtil. MESSAGE, msgContentString); broadcastAll (content) ;}else {try {String content = MessageUtil. sendContent (MessageUtil. MESSAGE, mapContent); singleChat (fromName, toName, content);} catch (IOException e) {e. printStackTrace () ;}} System. out. println (message from client: + message); broadcastAll (message);} private void singleChat (String fromName, String toName, String mapContent) throws IOException {String msgContentString = fromName + + toName +: + mapContent; String contentTemp = MessageUtil. sendContent (MessageUtil. MESSAGE, msgContentString); boolean isExit = false; for (HttpSession key: onlineUsers. keySet () {if (key. getAttribute (user ). equals (toName) {isExit = true ;}} if (isExit) {for (HttpSession key: onlineUsers. keySet () {if (key. getAttribute (user ). equals (fromName) | key. getAttribute (user ). equals (toName) {onlineUsers. get (key ). session. getBasicRemote (). sendText (contentTemp) ;}} else {String content = MessageUtil. sendContent (MessageUtil. MESSAGE, the customer service is not online, please leave a MESSAGE ...); broadcastAll (content) ;}} private void sendOffLine (String fromName, String toName) throws IOException {String msgContentString = toName + not online; String content = MessageUtil. sendContent (MessageUtil. MESSAGE, msgContentString); for (HttpSession key: onlineUsers. keySet () {if (key. getAttribute (user ). equals (fromName) | key. getAttribute (user ). equals (toName) {onlineUsers. get (key ). session. getBasicRemote (). sendText (content) ;}} private static void broadcastAll (String msg) {for (HttpSession key: onlineUsers. keySet () {try {onlineUsers. get (key ). session. getBasicRemote (). sendText (msg);} catch (IOException e) {e. printStackTrace () ;}}@ OnError public void onError (Session session, Throwable error) {System. out. println (error occurred); error. printStackTrace ();} private String getNames () {String names =; for (HttpSession key: onlineUsers. keySet () {String name = (String) key. getAttribute (user); names + = name +,;} String namesTemp = names. substring (0, names. length ()-1); return namesTemp;} public static synchronized int getOnlineCount () {return onlineCount;} public static synchronized void addOnlineCount () {ChatServlet. onlineCount ++;} public static synchronized void subOnlineCount () {ChatServlet. onlineCount --;}}
The front-end page has not changed. It is tested and feasible !!!