Tomcat erecting a simple websocket server

Source: Internet
Author: User
Tags tomcat server

Environment:
JDK 8
Eclipse-oxygen
Tomcat 7.088

    1. Build a Maven project in eclipse


      Click Next

      Like, pick that Maven-archetype-webapp, click Next.

      Write your name at the group ID and artifact ID, and start your own, click Finish

      This will be built, leave the error first.
      Open Pom.xml, go to Riga content

      Join:
      <dependency>   <groupId>javax.websocket</groupId>   <artifactId>javax.websocket-api</artifactId>   <version>1.0</version>     <scope>provided</scope></dependency>

      Again to solve the problem of error
      Start with a new folder,libs under your project

      Find your Tomcat directory/lib/

      Put the two jar pack in the box: Serverlet-api.jar Websocket-api.jar to the Libs folder you just built.

      And then put the two jar package add to Build Path

      This will not be an error, that is to say WebSocket server development ready OK.

Let's start writing the service.

With annotation injection, a script is ok

Package Com.r.server;import Java.io.ioexception;import Java.util.concurrent.concurrenthashmap;import  javax.websocket.*; Import Javax.websocket.server.ServerEndpoint; @ServerEndpoint ("/ws") public class WSServer {///static variable, used to record the current number of online connections.      It should be designed to be thread-safe.      private static int onlinecount = 0;    private static concurrenthashmap<session, wsserver> ssmap= new concurrenthashmap<session, wsserver> ();      A connection session with a client, which is required to send data to the client private session session; /** * Connection established method of successful call * @param session optional parameters. Session is a connection to a client, it needs to send data to the client */@OnOpen public void OnOpen (session session) {this.session =          Session        Ssmap.put (session, this);           Addonlinecount (); Online number plus 1 System.out.println ("New connection added!")      The current number of online people is "+ getonlinecount ());        }/** * method to close the call */@OnClose public void OnClose () {ssmap.remove (this.session);           Subonlinecount (); Online number minus 1 System.out.println ("There is a connectionShut down!      The current number of online people is "+ getonlinecount ());      /** * The method that is called after receiving the client message * @param message sent by the client * @param session Optional Parameters */@OnMessage          public void OnMessage (String message, session session) {SYSTEM.OUT.PRINTLN ("Message from client:" + message);        WSServer tmp = Ssmap.get (session);        try {tmp.sendmessage (message);        } catch (IOException E1) {e1.printstacktrace (); }}/** * Called when an error occurred * @param session * @param error */@OnError public void OnError (Se          Ssion session, throwable error) {System.out.println ("error occurred");      Error.printstacktrace (); }/** * This method is not the same as the above methods.      Without annotations, it is based on the method you need to add.          * @param message * @throws IOException */public void SendMessage (String message) throws ioexception{          This.session.getBasicRemote (). SendText (message);      This.session.getAsyncRemote (). SendText (message); } public static synchronizedint Getonlinecount () {return onlinecount;      } public static synchronized void Addonlinecount () {wsserver.onlinecount++;      } public static synchronized void Subonlinecount () {wsserver.onlinecount--; }}

This code is also copied from the Internet, but after my modification

@ServerEndpoint("/ws")

This line of code indicates that the address of this websockt server is when the project is running on the Tomcat server:
Ws://localhost:8080/web2/ws, where Web2 is the Artifect Id of the previous project, this example is WEB2
Each session here is a connection to each client.
Ssmap is a thread-safe map that joins clients to this map whenever a client connects
The original OnMessage method, is to receive the message after the message sent to all clients, a little chat room meaning, I changed it, who sent the message to send back to WHO

Then modify the index.jsp (this is the test)

<%@ page contenttype= "Text/html;charset=utf-8"%> 

Finally add the project to Tomcat and run Tomcat (operating in Eclipse)

Then open the browser, 360 Ah, Firefox, Chrome, whatever, enter the path to this project
Http://localhost:8080/web2
This will open index.jsp
Open post page Auto Connect websocket service

Sends a message that the server receives and returns to the client

Click Close WebSocket Connection will disconnect

These operations are also shown on the Tomcat server

This is the simple server-side and test JSP page

Tomcat erecting a simple websocket server

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.