Recently busy, for my website added chat room features, where the main use of WebSocket technology, then HTML5 a new technology
Controller section
Package Main.java.web.news;import java.io.IOException; Import Java.util.concurrent.CopyOnWriteArraySet; Import javax.websocket.*; Import Javax.websocket.server.ServerEndpoint; /** * @ServerEndpoint Annotation is a class-level annotation, its function is mainly to define the current class as a websocket server side, * The value of the annotation will be used to listen to the user connection terminal access URL address, The client can use this URL to connect to the WebSocket server */@ServerEndpoint ("/websocket") public class Newsserver {///static variable, which is 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<newsserver> Websocketset = new Cop Yonwritearrayset<newsserver> (); 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 = s Ession; Websocketset.add (this); Add Addonlinecount () in set; Online number plus 1 SYSTEM.OUT.PRINTLN ("New connection Added! The current number of online people 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 ()); /** * Method called after receiving a client message * @param message sent by client * @param session optional parameter */@OnMessage Pub LIC void OnMessage (String message, session session) {SYSTEM.OUT.PRINTLN ("Message from client:" + message); Mass message for (Newsserver Item:websocketset) {try {item.sendmessage (message); } catch (IOException e) {e.printstacktrace (); Continue }}}/** * called * @param session * @param error */@OnError public void OnError (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{ This.session.getBasicRemote (). SendText (message); This.session.getAsyncRemote (). SendText (message); } public static synchronized int Getonlinecount () {return onlinecount; } public static synchronized void Addonlinecount () {newsserver.onlinecount++; } public static synchronized void Subonlinecount () {newsserver.onlinecount--; } }
JSP and JS sections
<script type= "Text/javascript" > var websocket = null; var Nameleng = $ ("#userDetailDiv"). Text (). Split ("@") [0].length; var name = $ ("#userDetailDiv"). Text (). Split ("@") [0].substring (4,nameleng); /*//Determine if the current browser supports WebSocket if (' WebSocket ' in window) {WebSocket = new WebSocket ("Ws://localhost:8288/cptidewe B/websocket "); } else {alert (' current browser not WebSocket '); }//Connection error callback Method Websocket.onerror = function () {setmessageinnerhtml ("WebSocket connection error"); }; The callback method Websocket.onopen = function () {setmessageinnerhtml ("Join Problem Group") was successfully established by the connection; }; The callback method that receives the message Websocket.onmessage = function (event) {setmessageinnerhtml (event.data); }; callback method for connection Shutdown websocket.onclose = function () {setmessageinnerhtml ("Close problem Group"); }; Listen to the window Shutdown event, when the window is closed, actively to close the WebSocket connection, to prevent the connection has not been disconnected and close the window, the server side will throw an exception. Window.onbeforeunload = function () {closewebsocket (); }; *//To display the messageShown on the Web page function setmessageinnerhtml (InnerHTML) {document.getElementById (' message '). InnerHTML +=innerhtml + ' &L T;br/> '; var content = document.getElementById (' message '); Content.scrolltop = Content.scrollheight; }//Close WebSocket connection function Closewebsocket () {var mydate = new Date (); var mytime=mydate.tolocaletimestring (). substring (2,mydate.tolocaletimestring (). length); var message = mytime+ "" +name+ ": Exit Problem Group"; Websocket.send (message); Websocket.close (); $ ("#chatView"). Hide ();//Hidden Div $ ("#startChatView"). Show (); }//Open WebSocket Connect function Openwebsocket () {$ ("#chatView"). Show ();//Hide Div $ ("#startChatView"). Hide ();//Judge when Does the previous browser support WebSocket if (' WebSocket ' in window) {WebSocket = new WebSocket ("Ws://10.129.9.115:8081/cptideweb/web Socket "); } else {alert (' current browser not WebSocket '); }//Connection error callback Method Websocket.onerror = function () {SetmessageinnerhTML ("WebSocket connection error"); }; The callback method Websocket.onopen = function () {/* setmessageinnerhtml ("Join Problem Group") established by the connection successfully; */var mydate = new Date (); var mytime=mydate.tolocaletimestring (). substring (2,mydate.tolocaletimestring (). length); var message = mytime+ "" +name+ ": Join the problem group"; Websocket.send (message); }; The callback method that receives the message Websocket.onmessage = function (event) {setmessageinnerhtml (event.data); }; callback method for connection Shutdown websocket.onclose = function () {setmessageinnerhtml ("Close problem Group"); }; Listen to the window Shutdown event, when the window is closed, actively to close the WebSocket connection, to prevent the connection has not been disconnected and close the window, the server side will throw an exception. Window.onbeforeunload = function () {closewebsocket (); }; }//Send Message function Send () {//get time var mydate = new Date (); var mytime=mydate.tolocaletimestring (). substring (2,mydate.tolocaletimestring (). length); var message = mytime+ "" +name+ ":" +document.getelementbyid (' text '). Value; Websocket.send (message); document.getElementById (' tExt '). value= ""; } </script>
<!--new Question page--<div id= "Chatview" style= "position:fixed;bottom:0;width:400px;height:300px;right:0px; Margin-bottom:0px;z-index:9999;display:none "> <div class=" Panel Panel-default "style=" Bottom:0px;marg in-bottom:0px "> <div class=" panel-heading "> Discussion room </div> <div id= "message" class= "Panel-body" style= "Height:220px;overflow:scroll" > </div>
You can customize it to your own features.
Html WebSocket build chat room in lower right corner