Only two files are required, one server, one front end, and the example is to emulate a simple chat program:
Service side:
PackageCom.test.websocket;Importjava.io.IOException;ImportJava.util.concurrent.CopyOnWriteArraySet;ImportJavax.websocket.OnClose;ImportJavax.websocket.OnError;ImportJavax.websocket.OnMessage;ImportJavax.websocket.OnOpen;Importjavax.websocket.Session;Importjavax.websocket.server.ServerEndpoint; @ServerEndpoint ("/chat") Public classMywebsocket {//a static variable that is used to record the current number of online connections. It should be designed to be thread-safe. Private Static intOnlinecount = 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 Private StaticCopyonwritearrayset<mywebsocket> Websocketset =NewCopyonwritearrayset<mywebsocket>(); //a connection session with a client that needs to send data to the client PrivateSession session; /*** Connection Establishment method for successful invocation *@paramOptional parameters for session. Session is a connection to a client, it needs to send data to the client*/@OnOpen Public voidOnOpen (Session session) { This. session =session; Websocketset.add ( This);//Add in SetAddonlinecount ();//online number plus 1SYSTEM.OUT.PRINTLN ("New connection Added! The current number of people online is "+Getonlinecount ()); } /*** Method of connection close call*/@OnClose Public voidOnClose () {Websocketset.remove ( This);//Remove from SetSubonlinecount ();//online number minus 1System.out.println ("There's a connection off!") The current number of people online is "+Getonlinecount ()); } /*** Method called after receiving a client message *@parammessage sent over by the client *@paramSession Optional Parameters*/@OnMessage Public voidonMessage (String message, session session) {SYSTEM.OUT.PRINTLN ("Message from client:" +message); //Mass Message for(Mywebsocket item:websocketset) {Try{item.sendmessage (message); } Catch(IOException e) {e.printstacktrace (); Continue; } } } /*** Called when an error occurs *@paramSession *@paramError*/@OnError Public voidOnError (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. * @parammessage *@throwsIOException*/ Public voidSendMessage (String message)throwsioexception{ This. Session.getbasicremote (). SendText (message); //this.session.getAsyncRemote (). SendText (message); } Public Static synchronized intGetonlinecount () {returnOnlinecount; } Public Static synchronized voidAddonlinecount () {Mywebsocket.onlinecount++; } Public Static synchronized voidSubonlinecount () {Mywebsocket.onlinecount--; } }
Front:
<HTML><Body>Welcome<BR/> <inputID= "text"type= "text" /> <Buttononclick= "Send ()">Send</Button> <Buttononclick= "Closewebsocket ()">Close</Button> <DivID= "message"></Div> </Body><Scripttype= "Text/javascript"> varWebSocket= NULL; //determine if the current browser supports WebSocket if('WebSocket' inchwindow) {WebSocket= NewWebSocket ("Ws://localhost:8072/worktest/chat"); } Else{alert ('Not support WebSocket'); } //callback method where the connection error occurredWebsocket.onerror= function() {setmessageinnerhtml ("Error"); }; //callback method for successful connection establishmentWebsocket.onopen= function(event) {setmessageinnerhtml ("Open"); }; //callback method for receiving messageWebsocket.onmessage= function() {setmessageinnerhtml (event.data); }; //callback method for connection shutdownWebsocket.onclose= function() {setmessageinnerhtml ("Close"); }; //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() {websocket.close (); }; //to display a message on a Web page functionsetmessageinnerhtml (InnerHTML) {document.getElementById ('message'). InnerHTML+=InnerHTML+ '<br/>'; } //Close Connection functionClosewebsocket () {websocket.close (); } //Send Message functionSend () {varmessage=document.getElementById ('text'). Value; Websocket.send (message); } </Script></HTML>
WebSocket Simple Example