WebSocket Protocol is a new protocol for HTML5. It implements browser-to-server full-duplex communication (Full-duplex). For details, please refer to the relevant information, below I will demonstrate a simple page and server communication simple sample.
Create a new Web project based on the tomcat-7 version (the WebSocket feature is not implemented in versions less than 6))
Introduction of Tomcat7-websocket.jar and Websocket-api.jar in the Tomcat/lib directory to Classpath
New Websocketconfig.java as follows
This time using the annotation method
ImportJava.util.Set;ImportJavax.websocket.Endpoint;ImportJavax.websocket.server.ServerApplicationConfig;ImportJavax.websocket.server.ServerEndpointConfig; Public classWebsocketconfigImplementsserverapplicationconfig{@Override PublicSet<serverendpointconfig>Getendpointconfigs (Set<class<?extendsEndpoint>>scanned) { return NULL; } @Override PublicSet<class<?>> getannotatedendpointclasses (set<class<?>>scanned) { //back to scanned returnscanned; }}
Writing Echosocket Code
ImportJavax.websocket.OnClose;ImportJavax.websocket.OnMessage;ImportJavax.websocket.OnOpen;Importjavax.websocket.Session;Importjavax.websocket.server.ServerEndpoint; @ServerEndpoint ("/zqq/echo") Public classEchosocket { PublicEchosocket () {Super(); } @OnOpen Public voidOpen (Session session) {SYSTEM.OUT.PRINTLN ("id" +Session.getid ()); } @OnMessage Public voidmessage (Session session,string msg) {System.out.println ("SessionID" + session.getid () + ":" +msg); }}
At this point, write the client echo.jsp
<%@ page language= "Java"Import= "java.util.*" pageencoding= "UTF-8" iselignored= "false"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >var ws;
WebSocket, the protocol starts with the WS var target= "Ws://${pagecontext.request.remotehost}:8080${pagecontext.request.contextpath}/zqq/echo"; function Subopen () {if(' WebSocket 'in window) {ws=NewWebSocket (target); } Else if(' Mozwebsocket 'in window) {ws=NewMozwebsocket (target); } Else{alert (' WebSocket is not supported by this browser. '); return; } ws.onmessage=function (event) {console.info (event.data); Console.info (document.getElementById ("H1"). Value); document.getElementById ("H1"). innerhtml+=event.data+ ""; }; } function Subsend () {var text= document.getElementById ("Input"). Value; //alert (text);ws.send (text); document.getElementById ("Input"). Value= ""; }</script>At this point the program is deployed to Tomcat to be accessible, remember to open the channel first, enter the text on the line
The first time to write something, if there are errors please advise, continue to learn ....
Use WebSocket to make Web pages and servers communicate