WebSocket Echo Example based on Tomcat run HTML5

Source: Internet
Author: User
Tags echo message

One: Overview

As one of the new features of HTML5 websocket components, in the real-time requirements of the Web application development is still a certain use, the high version of IE, Chrome, FF browser support WebSocket, The standard WebSocket communication is based on the RFC6455 implementation of the server-side handshake with the client and the message. If the websocket communication is not too understanding, you can view the RFC document, simply by sending an HTTP request to achieve a handshake, the stateless HTTP communication protocol further upgrade to a stateful communication protocol, while the WebSocket also supports sub-protocol options and secure transmission. The standard websocket connection URL begins with WS and, if TLS-based, begins with WSS. Based on the websocket can be easily developed based on web chat programs, a variety of web message notifications and push notifications.

If you want to pick a grilled websocket of this life, still remember the earliest based on HTTP polling implementation of instant Web page communication way, that way more consumption of resources, so someone improved programming cometd long connection, but in essence is the new, But WebSocket's appearance just solves these problems, but many browser's low version still does not support WebSocket, thus also has spawned some JS communication frame which based on websocket idea Realization, They are more like sockjs and Socket.io, they all claim to support websocket, then if the browser side does not support the native WebSocket, they will automatically enable the fallback option to use other such as Ajax, HTTP polling, long polling/connection, Even flash sockets and other mechanisms to achieve analog websocket work, but their biggest disadvantage is that if the client use these frameworks, the server must use them, or wait for developers is a lot of unavoidable problems, and many are non-solution. The main reason is that they implement their own set of protocols, and do not manipulate the data in their format to play. Gossip says a little bit more.

Two: implementation steps

TOMCAT7 High version of the implementation of the WebSocket server-side RFC6455 standard protocol, you can communicate with the browser-side websocket, the first step is to do the following:

1. Install the high version jdk–jdk8

2. Install Tomcat 7.0.64

3. Build a Dynamic Web project in eclipse

According to the JSR standard, the standard interface for implementing WebSocket in Java can be based on annotations, and Tomcat is doing well, and we can create a websocket echo server only if we implement the following code:

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.getbas Icremote (). 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 Publ         IC 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 (). lengt            h); 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, you first need to add the following configuration to Web. xml:

<listener><listener-class>org.apache.tomcat.websocket.server.wscontextlistener</listener-class ></listener>

then implement the Serverapplicationconfig interface, implemented 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<serverendpointconfig> getendpointconfigs (set<class<? Extends endpoint>> scanned) {set<serverendpointconfig> result = new Hashset<serverendpointconfig> () ;/*if (Scanned.contains (Echowschatsever.class)) {Result.add (ServerEndpointConfig.Builder.create ( Echowschatsever.class, "/echo"). Build ());} */return result;} @Overridepublic set<class<?>> getannotatedendpointclasses (set<class<?>> scanned) {Set< class<?>> results = new hashset<class<?>> (); 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 page echo.html with the following content:

Three: Run and test

After the package is deployed to Tomcat, launch the Chrom browser and enter the address:

Http://localhost:8080/websocket/echo.html


Later, I also found that the Tomcat implementation WebSocket server side actually does not support the sub-protocol

Not the same as the test URL results on 3W.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

WebSocket Echo Example based on Tomcat run HTML5

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.