WebSocket build tutorial, websocket build
How to build a websocket?
The first step is to compile a simple jsp file, which mainly includes websocket connection and four websocket response events.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%-- <jsp:include page="/js/jspfunc/supplierBackGroundMan/supplierBackGroundMan.jsp" /> --%><% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;%><!DOCTYPE html>
Step 2: configure the struts. xml configuration file
<! -- Do not intercept ws requests --> <constant name = "struts. action. excludePattern" value = "/websocket/chat"> </constant>
Step 3: Compile the background code
// OnOpen this method will be called when we create a connection to the server. // OnClose this method will be called when we close a connection to the server. // OnError this method is called when a client-server communication error occurs. // The onMessage event provides a data attribute that can contain the Body of the message. The Body of a message must be a string that can be serialized or deserialized to transfer more data. Package com. nmfz. app. websocket; import java. io. IOException; import java. io. printWriter; import java. util. arrayList; import java. util. date; import java. util. hashMap; import java. util. list; import java. util. map; import java. util. set; import java. util. concurrent. atomic. atomicInteger; import javax. annotation. resource; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; impor T 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 org. apache. commons. logging. log; import org. apache. commons. logging. logFactory; import org. apache. struts2.ServletActionContex T; import org. directwebremoting. json. jsonUtil; import org. directwebremoting. json. parse. jsonParseException; import org. springframework. beans. factory. annotation. autowired; import org. springframework. beans. factory. annotation. qualifier; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; import org. springframework. context. support. F IleSystemXmlApplicationContext; import org. springframework. web. context. contextLoader; import org. springframework. web. context. support. webApplicationContextUtils; import com. alibaba. fastjson. JSON; import com. nmfz. app. action. sharedFarmUsers; import com. nmfz. app. manager. sharedFarmUsersManager; import com. nmfz. app. manager. impl. sharedFarmUsersManagerImpl; import net. sf. json. JSONObject;/*** @ ServerEndpoint annotation is A class-level annotation. Its function is to define the current class as a websocket server. The annotation value is used to listen to the terminal access URL address connected to the user. * Aggregator: The gethttpsessionaggregator can be used to obtain HttpSession in the onOpen method, and then the spring service can be obtained through the ServletContext container of HttpSession to inject spring bean in disguise in websocket. * @ Author zho */@ ServerEndpoint (value = "/websocket/chat", aggregator = GetHttpSessionConfigurator. class) public class MyWebSocket {// static variable used to record the number of current online connections. It should be designed to be thread-safe. Private final static AtomicInteger onlineCount = new AtomicInteger (0); // thread security Set of the concurrent package, used to store the MyWebSocket object corresponding to each client. To implement communication between the server and a single client, Map can be used for storage. The Key can be the user ID // private static CopyOnWriteArraySet
WebSocketSet = new CopyOnWriteArraySet
(); Private static List
Clients = new ArrayList <> (); // connection Session with a client, which needs to be used to send data to the Client private session Session; private HttpSession httpSession; // ngs static int userid; @ OnOpen public void onOpen (Session session, EndpointConfig config) throws IOException, InterruptedException {this. session = session; this. httpSession = (HttpSession) config. getUserProperties (). get (HttpSession. class. getName (); clients. add (this); // add the current client to the set MyWebSocket. onlineCount. incrementAndGet (); // online shujia 1 sendMessage ("open"); // send this user the latest stealing record} @ OnClose public void onClose () throws IOException, interruptedException {clients. remove (this); // Delete MyWebSocket from set. onlineCount. decrementAndGet (); // online quantity minus 1 System. out. println ("close") ;}@ OnMessage public void onMessage (String message, EndpointConfig config) throws IOException, InterruptedException {sendMessage (message) ;}@ OnError public void onError (Throwable t) throws Throwable {t. printStackTrace (); System. out. println ("error");}/*** send a message to the client * @ param message * @ throws IOException */public void sendMessage (String message) throws IOException {// dialog between yourself and yourself. try {// this. session. getBasicRemote (). sendText (message); // synchronize this. session. getAsyncRemote (). sendText (message); // asynchronous} catch (Exception e) {e. printStackTrace ();} // MyWebSocket. broadcast (message);}/*** send a message to a user ** @ param userName * @ param message * // * public void sendMessageToUser (String userName, TextMessage message) {for (MyWebSocket client: clients) {if (client. getAttributes (). get ("websocket_username "). equals (userName) {try {if (client. isOpen () {client. sendMessage (message) ;}} catch (IOException e) {e. printStackTrace () ;} break ;}} * // * broadcast: traverses the client set and sends messages. Pay attention to the session used for sending and use session. getBasicRemote (). sendText (msg) sends a message */public static void broadcast (String msg) {for (MyWebSocket client: clients) {// traverse all try {// if this client is already online synchronized (client) {client. session. getBasicRemote (). sendText (msg); // send message} catch (IOException e) {// if this client is not online // log. debug ("Chat Error: to the user" + client. getUser (). getUsername () + "failed to send message", e); clients. remove (client); try {client. session. close ();} catch (IOException e1) {// Ignore} // String message = String. format ("-- % s", client. user. getUsername (), "offline. "); // broadcast (message) ;}}/ *** @ trigger event * @ param msg * @ param pa1 */public void triggerEvent (String msg) {try {onMessage (msg, null);} catch (Exception e) {e. printStackTrace () ;}}/*** get the current number of online users * @ return */public static int currentOnline () {return onlineCount. get ();}
Step 4: compile a subclass GetHttpSessionConfigurator that inherits the aggregator. You can use GetHttpSessionConfigurator to obtain HttpSession in the onOpen method, and then use the ServletContext container of HttpSession to obtain the spring service, implement disguised injection of spring bean in websocket.
package com.nmfz.app.websocket;import javax.servlet.http.HttpSession;import javax.websocket.HandshakeResponse;import javax.websocket.server.HandshakeRequest;import javax.websocket.server.ServerEndpointConfig;import javax.websocket.server.ServerEndpointConfig.Configurator;public class GetHttpSessionConfigurator extends Configurator{ @Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); if(httpSession != null){ config.getUserProperties().put(HttpSession.class.getName(), httpSession); } } }