Example of using WebSocket to implement chat in Java7 and TOMCAT8 environments

Source: Internet
Author: User
Tags throwable

The case is developed and run in the apache-tomcat-8.0.15 and jdk1.8.0_25 environments. However, the title is Java7, it does not affect, the code does not involve any jdk1.8.x-related code. In addition, the reason to clear the software version, one is to ensure that the case can have a clear implementation of the background, the second is websocket to achieve tomcat7.x and tomcat8.x there is a great difference.


The Java API for WebSocket (JSR 356) is our main focus here in the EE specification. WEBSOCKET-API provides a Java implementation Websocket interface, the most important of which are the following classes and annotations such as:

650) this.width=650; "Src=" http://s3.51cto.com/wyfs02/M02/54/32/wKiom1R71HfSnxu9AATraxMbUG0847.jpg " Title= "Javax.websocket.png" alt= "Wkiom1r71hfsnxu9aatraxmbug0847.jpg"/>

Explain:

1. Top 4 annotations Onclose,onerror, OnOpen, OnMessage used to annotate a Pojo method for handling WebSocket requests;

2.Endpoint and Endpointconfig define the interface method of endpoint and endpoint related configuration respectively;

3.ClientEndpoint and Serverendpoint respectively define the interface method of client and server end endpoints;

4.Decoder and encoder are decoding and coding interface method definitions respectively;

5.Session is the WebSocket session interface method definition associated with endpoint.

There are other interfaces as well, here as a preliminary understanding of the Java WebSocket API listing only the most necessary ones.


TOMCAT8.X provides a standard implementation of the JAVAEE7, where the WebSocket 1.1 specification is implemented. The dependent environment used for its development is tomcat8.x JDK7. tomcat8.x provides a server-side implementation that needs to be implemented by other implementations such as Java_websocket.

tomcat8.x to WebSocket implementation feel very clear, since the API defines the WebSocket related annotations and session so tomcat8.x implementation naturally have corresponding processing and implementation, is a simple relationship description.

 650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/54/31/wKioL1R71y-yvpatAAI1MX-cI-o472.jpg "title=" Tomcat.png "alt=" Wkiol1r71y-yvpataai1mx-ci-o472.jpg "/>

Explain:

    1. Tomcat's Wssession class implements the session interface in the Java WebSocket API

    2. Pojoendpointbase and its subclasses handle classes or annotations related to endpoint

    3. There is a dependency between the endpointconfig,endpoint and the implementation class of the session


By understanding the Java Websocket API and the implementation of tomcat8.x, it is considered that the use of Java Websocket requires familiarity with key classes or interfaces such as: Endpoint,endpointconfig,client and Server, Encoder and Decoder,session,messagehandler.


The above outlines the implementation of tomcat8.x to Java WebSocket, the information about the WebSocket specification can be consulted:

RFC6455: http://tools.ietf.org/html/rfc6455

WebSocket Server-side implementations: Https://java.net/projects/websocket-spec/pages/WebSocketAPIs


Here's a sample code to show real-time chat based on WebSocket

1. Server-side implementation

package t8j8.examples;import java.io.ioexception;import java.util.set;import  java.util.concurrent.copyonwritearrayset;import javax.websocket.onclose;import  javax.websocket.onerror;import javax.websocket.onmessage;import javax.websocket.onopen;import  javax.websocket.session;import javax.websocket.server.pathparam;import  Javax.websocket.server.ServerEndpoint; @ServerEndpoint (value =  "/ws/chat/{nickname}") public  class chat {    /**     *  Connection Object Collection       */    private static final set<chat> connections  = new CopyOnWriteArraySet<Chat> ();    private string  nickname;    /**     * websocket session      */    private Session session;    public chat ()  {    }    /**      *  Open Connection      *      *  @param   session     *  @param  nickName     */      @OnOpen     public void onopen (session session,              @PathParam (value =  "nickname")   String nickname)  {        this.session = session;         this.nickName = nickName;         connections.add (This);        string  Message = string.format ("system> %s %s", this.nickname,                  " has joined.");         chat.broadcast (message);    }     /**     *  Close Connection      */      @OnClose     public void onclose ()  {         connections.remove (this);         string message  = string.format ("system> %s, %s", this.nickname,                  " has disconnection.");         chat.broadcast (message);    }     /**     *  Receive Information      *       *  @param  message     *  @param nickName     */     @OnMessage     public  void onmessage (string message,              @PathParam (value =  "nickname")  string nickname)  {         chat.broadcast (nickname +  ">"  + message);     }    /**     *  Error message Response      *       *  @param  throwable     */      @OnError     public void onerror (throwable throwable)  {         system.out.println (Throwable.getmessage ());     }    /**     *  send or broadcast information      *       *  @param  message     */    private static  void broadcast (string message)  {        for  (chat chat : connections)  {             try {                 synchronized  (chat)  {                     chat.session.getbasicremote (). SendText (Message);                 }             } catch  (ioexception e)  {                 connections.remove ( Chat);                 try {                      Chat.session.close ();                 } catch  (IOEXCEPTION&NBSP;E1)  {                 }                 chat.broadcast (String.Format ("system> %s %s",  chat.nickname,                          " has bean disconnection.");             }         }    }}

Description

The value value of the Serverendpoint annotation in the code has a nickname parameter placeholder called the Path parameter, which can be set and obtained through the annotation of the method parameter (@PathParam);

There is only one way to Onclose,onopen,onerror annotations in a class that endpoint annotations, and the OnMessage annotation method can have many of this easy to understand because WebSocket can handle the information text,binary, TextStream and so on.


2. Client implementation

If you use MAVEN, you can add a dependency on the Java_websocket jar.

<dependency> <groupId>org.java-websocket</groupId> <artifactid>java-websocke        T</artifactid> <version>1.3.0</version> <scope>runtime</scope> </dependency>


If you are developing a Web client, you can choose a browser that supports WebSocket, using HTML5 technology.


Here is the code that uses Java_websocket to implement the client:

Package t8j8.examples.client;import java.net.uri;import java.net.urisyntaxexception;import  java.util.scanner;import org.java_websocket.client.websocketclient;import org.java_ websocket.drafts.draft_17;import org.java_websocket.handshake.serverhandshake;public class  Testtocatwebsocket {    public static void main (String[] args)  throws urisyntaxexception {        string url  =  "ws://localhost:8080/t8j8/ws/chat/"  + args[0];         websocketclient wc = new websocketclient (New uri (URL), new  Draft_17 ())  {             @Override              public void onopen (ServerHandshake  handshakedata)  {                system.out.println ( Handshakedata.gethttpstatusmessage ());             }             @Override              public void onmessage (String message)  {                  SYSTEM.OUT.PRINTLN (message);            }              @Override              public void onerror (Exception ex)  {             }              @Override &NBSP;&NBSP;&NBSP;&NBSP;&NBSp;       public void onclose (int code, string  Reason, boolean remote)  {             }        };         Wc.connect ();        while  (true)  {             scanner scanner = new scanner (System.in);             String message =  Scanner.nextline ();            if  ( Message.equals ("Q"))  {                 wc.close ();                 break;            }             scanner.close ();             wc.send ( message);         }    }}

Description

The client is to describe the creation of the new Draft_17 () object, which can be understood by the class name. As the WebSocket standard has not been released, so the implementation is based on the draft, and here the draft_17 corresponds to the WebSocket version is: "" Sec-websocket-version "," "" Unfortunately, Java _websocket package delayed the content of the update, the name appears misunderstood people place.


3. Start chatting

Deploy the server-side program to start the client program (you need to add nickname parameters).

Here are the chats, Tom and Jack, respectively.

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/54/33/wKiom1R74rWjTwRAAAENkee9KzI276.jpg "style=" float: none; "title=" Jack.png "alt=" Wkiom1r74rwjtwraaaenkee9kzi276.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/54/32/wKioL1R74z6z27UsAAFZ621cRio571.jpg "style=" float: none; "title=" Tom.png "alt=" Wkiol1r74z6z27usaafz621crio571.jpg "/>

At this point, the chat example with WebSocket implementation based on TOMCAT8 and JDK7 is over.

This article from "Mustang Red" blog, declined reprint!

Example of using WebSocket to implement chat in Java7 and TOMCAT8 environments

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.