1, the basic Environment: JDK-1.8.71, tomcat:apache-tomcat-8.0.33
2. Client code:
<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >2. Server-side code:Import Java.io.ioexception;import Java.util.concurrent.copyonwritearrayset;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; @ServerEndpoint (value= "/websocket") public Class Mywebsocket {//static variable, used to record the current number of online connections. It should be designed to be thread-safe. private static int onlinecount = 0; The thread-safe set of the concurrent package that holds the corresponding Mywebsocket object for each client. To enable the server to communicate with a single client, you can use a map to store it, where key can identify the user with private static copyonwritearrayset<mywebsocket> Websocketset = new Copyonwritearrayset<mywebsocket> (); A connection session with a client, which is required to send data to the client private session session; /** * Connection established method of successful call * @param session optional parameters. Session is a connection to a client, it needs to send data to the client */@OnOpen public void OnOpen (session session) {This.session = Session ; Websocketset.add (this); Add Addonlinecount () in set; Online number plus 1 System.out.println ("New connection added!") The current number of people online is"+ Getonlinecount ()); }/** * method to close the call */@OnClose public void OnClose () {websocketset.remove (this); Remove Subonlinecount () from set; Online number minus 1 System.out.println ("There's a connection off!") The current number of online people is "+ getonlinecount ()); /** * The method called after receiving the client message * @param message sent by the client * @param session optional parameter */@OnMessage Publi c void OnMessage (String message, session session) {SYSTEM.OUT.PRINTLN ("Message from client:" + message); Mass message for (Mywebsocket Item:websocketset) {try {for (int i = 0;i < 3;i++) { Item.sendmessage ("Hello"); }} catch (IOException e) {e.printstacktrace (); Continue }}}/** * Called when an error occurred * @param session * @param error */@OnError public void Onerro R (Session session, throwable error) {System.out.println ("error occurred"); Error.printstacktrace (); }/** * This method is not the same as the above methods. Without annotations, it is based on the method you need to add. * @param message * @throws IOException */public void SendMessage (String message) throws ioexception{th Is.session.getBasicRemote (). SendText (message); This.session.getAsyncRemote (). SendText (message); } public static synchronized int Getonlinecount () {return onlinecount; } public static synchronized void Addonlinecount () {mywebsocket.onlinecount++; } public static synchronized void Subonlinecount () {mywebsocket.onlinecount--; }}
3. Compile the project locally and access through the browser: http://localhost:8080/HelloWorld/index.jspVisit the following page:
Open indicates that the WebSocket connection was successfully established.
4. Send a request to the background: Enter Hello in the text box of the page in the third step, and click the Send button:
The front desk displays as follows:
The day After tomorrow is printed information as follows:
5. Click the Close button
The foreground page outputs the following information:
The background output information is as follows:
6. End of Test
7, simple example does not show that websocket is very fashionable, very popular, the simplest is that its own requirements for the browser is very strict, for example, I use the IE8 to complete the above URL Access will report the following error:
According to the prompt, IE8 is not supported by WebSocket until IE10 above, and some other browsers have higher versions only.
WebSocket to HelloWorld