Use webSocket to enable webpage and server communication and websocket Communication
WebSocket protocol is a new HTML5 protocol. It enables full-duplex communication between the browser and the server ). For details, refer to the relevant materials. Here is a simple example of a simple page to communicate with the server.
Create a web Project (based on tomcat-7 (versions earlier than 6 do not implement the webSocket function ))
Introduce tomcat7-websocket.jar and websocket-api.jar under tomcat/lib directory to classpath
Create WebSocketConfig. java as follows
Annotation method used this time
Import java. util. set; import javax. websocket. endpoint; import javax. websocket. server. serverApplicationConfig; import javax. websocket. server. serverEndpointConfig; public class WebSocketConfig implements ServerApplicationConfig {@ Override public Set <ServerEndpointConfig> getEndpointConfigs (Set <Class <? Extends Endpoint >>> scanned) {return null ;}@ Override public Set <Class <?>> GetAnnotatedEndpointClasses (Set <Class <?> Scanned) {// return scanned ;}}
Write EchoSocket code
import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;@ServerEndpoint("/zqq/echo")public class EchoSocket { public EchoSocket() { super(); } @OnOpen public void open(Session session){ System.out.println("id " + session.getId()); } @OnMessage public void message(Session session,String msg){ System.out.println("sessionid " + session.getId() + " : " + msg); }}
At this time, 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"> // Websocket. The Protocol starts with ws var target = "ws: // $ {pageContext. request. remoteHost: 8080 $ {pageContext. request. contextPath}/zqq/echo "; function subOpen () {if ('websocket 'in window) {ws = new WebSocket (target);} else if ('your WebSocket' in window) {ws = new protected WebSocket (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>
Now you can access the application deployed on tomcat. Remember to open the channel first and enter the text.
I wrote something for the first time. If you have any errors, please advise and continue learning ....