Tomcat and jetty support for WebSocket

Source: Internet
Author: User

Company project needs, understand the next several support websocket framework. Previously used Jwebsocket to do some projects, relatively speaking, to change the source of Jwebsocket slightly complex, not two days a day can be done. A survey found, now many mainstream web framework has started to support websocket, have to sigh time too fast, technology progress too fast, in the micro-strategy of the years really wasted. Not much to say, first record today's research.


Tomcat:

The most containers used under the Java EE should be tomcat. When it comes to Tomcat's support for WebSocket, I have to mention that the current WebSocket protocol has evolved over several generations, and different browsers support this protocol differently, so if you're a server, it's best to support as many WebSocket protocol versions as possible.

Tomcat8 really supports jsr-356 (including support for WebSocket), TOMCAT7 supports some versions of WebSocket implementations that are incompatible jsr-356. Therefore, can use tomcat8 words, or try to use.


The code implementation is fairly straightforward, and the following is a sample, which requires only the TOMCAT8 base library and no other dependencies.

Import java.io.IOException;  Import Javax.websocket.OnClose;  Import Javax.websocket.OnMessage;  Import Javax.websocket.OnOpen;  Import javax.websocket.Session;  Import Javax.websocket.server.ServerEndpoint; @ServerEndpoint ("/websocket") public class Websockettest {@OnMessage public void OnMessage (String message, S Ession session) throws IOException, interruptedexception {//Print the client message for testing p          Urposes System.out.println ("Received:" + message);          Send the first message to the client Session.getbasicremote (). SendText ("This is the first server message");          Send 3 messages to the client every 5 seconds int sentmessages = 0;              while (Sentmessages < 3) {Thread.Sleep (5000); Session.getbasicremote (). SendText ("This was an intermediate server message.              Count: "+ sentmessages);          sentmessages++; }//Send a final message to the CLIent session.getbasicremote (). SendText ("The Last Server Message");      } @OnOpen public void OnOpen () {System.out.println ("Client connected");      } @OnClose public void OnClose () {System.out.println ("Connection closed");   }  }


Jetty:

Jetty, like Tomcat, is also a servlet container. If there is a difference, then the biggest difference is that Tomcat uses the BIO -processing method, which means that a request will be processed by a thread, even if the long connection is websocket, it will open a thread independently. As an ordinary Web server, Tomcat can easily cope with the time-consuming request/response. But if it is a long-connected websocket, then the trouble comes, for tens of thousands of users of chat and push, can not open tens of thousands of threads to deal with it. At this point, the performance of the jetty, jetty using NIO, a thread can handle multiple websocket long links, if your needs are a lot of time-consuming request or a large number of long connections, it is recommended to use jetty.


Jetty the implementation of websocket a bit around, the servlet is no longer inherited from the original HttpServlet, but inherited Websocketservlet. It is important to note that you import Jetty-util.jar and Jetty-websocket.jar two packages, otherwise class not found errors may occur.

Reverseajaxservlet.java:

Import Java.io.ioexception;import Java.util.date;import java.util.Random; Import Javax.servlet.servletexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.HttpServletResponse; Import Org.codehaus.jettison.json.jsonarray;import Org.eclipse.jetty.websocket.websocket;import Org.eclipse.jetty.websocket.WebSocketServlet;     /** * @author Mathieu Carbou ([email protected]) */public final class Reverseajaxservlet extends Websocketservlet {    Private final endpoints endpoints = new endpoints ();    Private final random random = new random (); Private final thread generator = new Thread ("Event generator") {@Override public void run () {WH Ile (!                    Thread.CurrentThread (). isinterrupted ()) {try {thread.sleep (Random.nextint (5000));                Endpoints.broadcast (New Jsonarray (). Put ("at" + New Date ()). ToString ()); } catch (Interruptedexception e) {Thread.currentthreaD (). interrupt ();     }            }        }    };        @Override public void Init () throws Servletexception {Super.init ();    Generator.start ();        } @Override public void Destroy () {generator.interrupt ();    Super.destroy (); } @Override Public WebSocket dowebsocketconnect (httpservletrequest request, String protocol) {return EN    Dpoints.newendpoint (); } @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexcepti    On, IOException {resp.getwriter (). Write ("11111"); }}

Endpoints.java:

Package Com.cn.test.chapter2.websocket;import Org.eclipse.jetty.websocket.websocket;import Java.util.Queue;import Java.util.concurrent.ConcurrentLinkedQueue; /** * @author Mathieu carbou ([email protected]) */final class Endpoints {    private final queue<endpoint> Endpoin ts = new concurrentlinkedqueue<endpoint> ();     void broadcast (String data) {//For        (Endpoint endpoint:endpoints) {//            endpoint.onmessage (data);/        }    }     void Offer (Endpoint Endpoint) {        endpoints.offer (Endpoint);    }     void Remove (Endpoint Endpoint) {        endpoints.remove (Endpoint);    }     Public WebSocket Newendpoint () {        return to new Endpoint (this);}    }

Endpoint.java

Import Java.io.ioexception;import Java.util.concurrent.ConcurrentLinkedQueue; Import Org.codehaus.jettison.json.jsonarray;import Org.eclipse.jetty.websocket.WebSocket;  /** * @author Mathieu Carbou ([email protected]) */class Endpoint implements Websocket.ontextmessage {protected         Connection _connection;         private endpoints endpoints;    private static int clientcounter = 0;         private int clientId = clientcounter++;    Public Endpoint (Endpoints endpoints) {this.setendpoints (endpoints);              } @Override public void onClose (int code, String message) {System.out.println ("Client disconnected");    This.endpoints.remove (this);          } @Override public void OnOpen (Connection Connection) {System.out.println ("Client connected");        _connection = connection;        try {this._connection.sendmessage (New Jsonarray (). put ("ClientID =" + ClientID). toString ()); } catch (IOException e) {//TODO auto-Generated catch block E.printstacktrace ();    } endpoints.offer (this);          } @Override public void OnMessage (final String data) {System.out.println ("Received data:" + data);    This.endpoints.broadcast (data);    } public Endpoints Getendpoints () {return endpoints;    } public void Setendpoints (endpoints endpoints) {this.endpoints = endpoints; }}




Accessibility tools:

In writing the server the most troublesome is to write the corresponding client to test, fortunately, Chrome has solved this problem for us. Download the chrome plugin WebSocket clinet makes it easy to connect to the server and send messages to the server.

Tomcat and jetty support for WebSocket

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.