Example of running HTML5 WebSocket echo Based on tomcat
I. Overview
As one of the new HTML5 features, WebSocket components are useful in WEB application development with certain real-time requirements. WEB socket is supported in the later versions of IE, Chrome, and FF browsers, the standard Websocket communication is based on RFC6455 to implement handshake and message sending between the server and the client. If you are not familiar with Websocket communication, you can view the RFC documentation. Simply put, you can send an HTTP request to shake hands between the two parties, the stateless HTTP Communication Protocol is further upgraded to a stateful communication protocol, and Websocket also supports sub-protocol options and secure transmission. The standard websocket URL starts with ws. If it is TLS-based, it starts with wss. Based on Websocket, you can easily develop web chat programs and various webpage message notifications and push notifications.
If you have to dig a piece of websocket, remember the earliest way to implement instant webpage Communication Based on HTTP polling, this method is resource-consuming, so someone has improved the programming CometD persistent connection method, but in essence it is still not changing, and the emergence of websocket just solves these problems, however, the earlier versions of many browsers still do not support websocket. Therefore, some JS communication frameworks based on the websocket concept have been developed. Among them, SockJS and socket have been compared. io, they all claim to support websocket, and if the browser does not support native websocket, they will automatically enable the fallback option to use other mechanisms, such as ajax, Http polling, long polling/connection, and even flash socket, to simulate websocket working methods, but their biggest drawback is that if the client uses these frameworks, the server must use them. Otherwise, waiting for developers is a lot of unavoidable problems, and many of them are unsolved. The main reason is that they implement their own protocol sets and cannot process data without their format. There are a lot of gossip.
II. Implementation steps
In the later version of Tomcat 7, the RFC6455 standard protocol on the websocket server can be implemented to communicate with websocket on the browser. The following steps must be done first:
1. Install JDK-JDK 8 with a higher version.
2. install tomcat 7.0.64
3. Create a dynamic web project in eclipse
According to the JSR standard, the standard interface for implementing websocket in Java can be implemented based on the annotation method, and tomcat is also well done. Only by implementing the following code can we create a websocket echo server:
package com.websocket.demo;import java.io.IOException;import java.nio.ByteBuffer;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;@ServerEndpoint(value = /echo)public class EchoExample {@OnMessagepublic void echoTextMessage(Session session, String msg, boolean last) {try {if (session.isOpen()) {System.out.println(received from client message = + msg);session.getBasicRemote().sendText(msg, last);}} catch (IOException e) {try {session.close();} catch (IOException e1) {}}}@OnOpen public void openConn(Session session) throws IOException { session.getBasicRemote().sendText(hello web socket); // means open it } @OnMessage public void echoBinaryMessage(Session session, ByteBuffer bb, boolean last) { System.out.println(send binary message...); try { if (session.isOpen()) { System.out.println(byte buffer lenghth : + bb.array().length); System.out.println(byte buffer content: + ((bb.array()[0]) & 0xff)); System.out.println(byte buffer content: + ((bb.array()[1]) & 0xff)); System.out.println(byte buffer content: + ((bb.array()[2]) & 0xff)); session.getBasicRemote().sendBinary(bb, last); } } catch (IOException e) { try { session.close(); } catch (IOException e1) { // Ignore } } }}
To start the websocket server in tomcat, add the following configuration in web. xml:
org.apache.tomcat.websocket.server.WsContextListener
Then implement the ServerApplicationConfig interface as follows:
/* * */package com.config.websocket.client;import java.util.HashSet;import java.util.Set;import javax.websocket.Endpoint;import javax.websocket.server.ServerApplicationConfig;import javax.websocket.server.ServerEndpointConfig;public class ScanWebSocketSeverConfig implements ServerApplicationConfig {@Overridepublic Set
getEndpointConfigs(Set
> scanned) {Set
result = new HashSet
();/*if (scanned.contains(EchoWsChatSever.class)) {result.add(ServerEndpointConfig.Builder.create(EchoWsChatSever.class, /echo).build());}*/return result;}@Overridepublic Set
> getAnnotatedEndpointClasses(Set
> scanned) {Set
> results = new HashSet
>();for (Class
clazz : scanned) {if (clazz.getPackage().getName().startsWith(com.websocket.)) {System.out.println(find end point : + clazz.getName());results.add(clazz);}}return results;}}
Create a Web page echo.html with the following content:
<Script> var ws = null; var count = 0; function setConnected (connected) {document. getElementById ('connect '). disabled = connected; document. getElementById ('disconnect '). disabled =! Connected; document. getElementById ('echo '). disabled =! Connected;} function connect () {var target = document. getElementById ('target '). value; if (target = '') {alert ('Please select server side connection implementation. '); return;} if ('websocket' in window) {ws = new WebSocket (target);} else if ('websocket 'in window) {ws = new protected WebSocket (target);} else {alert ('websocket is not supported by this browser. '); return;} ws. onopen = function () {SetConnected (true); log ('info: WebSocket connection opened. ') ;}; ws. onmessage = function (event) {log ('stored ed: '+ event. data); if (event. data instanceof ArrayBuffer) {var bytes = new Uint8Array (event. data); alert (bytes. length +: + bytes [0]) ;}}; ws. onclose = function (event) {setConnected (false); log ('info: WebSocket connection closed, Code: '+ event. code + (event. reason =? :, Reason: + event. reason) ;};} function disconnect () {if (ws! = Null) {ws. doClose (); ws = null;} setConnected (false);} function echo () {if (ws! = Null) {var message = document. getElementById ('message '). value; log ('sent: '+ message); ws. send (JSON. stringify ({'textmessage': message}); count ++} else {alert ('websocket connection not established, please connect. ') ;}} function log (message) {var echomsg = document. getElementById ('echomsg '); var p = document. createElement ('P'); p. style. wordWrap = 'break-word'; p. appendChild (document. createTextNode (message); echomsg. appendChild (p); while (echomsg. childNodes. length> 25) {echomsg. removeChild (console. firstChild);} echomsg. scrollTop = console. scrollHeight;} document. addEventListener (DOMContentLoaded, function () {// Remove elements with noscript class- Is not allowed in XHTML var noscripts = document. getElementsByClassName (noscript); for (var I = 0; I <noscripts. length; I ++) {noscripts [I]. parentNode. removeChild (noscripts [I]) ;}}, false); </script> URL-ws: // localhost: 8080/websocket/echo Connect Disconnect Here is a message! Echo messageIii. Running and Testing
After packaging and deploying tomcat, start the chrom browser and enter the address:
Http: // localhost: 8080/websocket/echo.html
Later, I also found that tomcat's websocket server does not support sub-protocols.
The test URL result is different from that of the 3W instance.