Java implementation of WebSocket

Source: Internet
Author: User

WebSocket API Introduction:

First look at a simple JavaScript code that calls the WebSockets API.

[JavaScript]View Plaincopy
  1. var  WS =  new  websocket ("WS: //echo.websocket.org");   
  2.   
  3. ws.onopen = function
  4.   
  5. ws.onmessage = function
  6.   
  7. ws.onclose = function
  8.   
  9. Ws.onerror = function(evt) {console.log ("websocketerror!");};

This code is only 5 lines in total, and now briefly outlines the meaning of these 5 lines of code.

The first line of code is to request a WebSocket object, the parameter is the server-side address that needs to be connected, the same as the HTTP protocol use//start, the URL of the WebSocket protocol uses ws://beginning, and the other secure WebSocket protocol uses wss:// Beginning.

The second line to the fifth behavior WebSocket object Registration Message handler function, WebSocket object supports altogether four messages OnOpen, OnMessage, OnClose and OnError, when browser and Websocketserver are connected successfully , the OnOpen message is triggered, and if the connection fails, the send, receive data fails, or the processing data error occurs, browser triggers the onerror message, and when browser receives the data sent by Websocketserver, the onmessage message is triggered. , the parameter evt contains the data transmitted by the server, and the OnClose message is triggered when browser receives a close connection request sent by the Websocketserver side. We can see that all actions are triggered by the message, so that the UI is not blocked, and the UI has a faster response time and a better user experience.


Realize:

@ServerEndpoint (value = "/websocket/{random}") public class WebSocket {private static final set<websocket> Conne        ctions = new copyonwritearrayset<websocket> ();     Private session session;      Private String random; Public WebSocket () {}//* This method executes when the WebSocket client connects to the server, and passes a session object to us to get this session, that is, we can     The client sends a message */@OnOpen public void Start (Session session, @PathParam ("random") String random) {this.random=random;        SYSTEM.OUT.PRINTLN (random);        This.session = session;        Connections.add (this);    }/* This method is automatically called when the client is closed/@OnClose public void End () {connections.remove (this); }/* Client sends a message to the server, this method is automatically called, and can get the data sent */@OnMessage public void Incoming (String message) {//N    Ever trust the client//sendbyip ("10.104.5.51", "only to the first");        System.out.println (random+ ":" +message);      Broadcast (message); }/* An exception occurred automaticallyExecute */@OnError public void OnError (Throwable t) throws Throwable {}/* Broadcast: Traverse the client set, send a message, note the session to be sent , send a message with Session.getbasicremote (). SendText (MSG) */public static void Broadcast (String msg) {for (WebSocket CLI                      Ent:connections) {//Traverse all try {//If this client is already online synchronized (client) { Client.session.getBasicRemote (). SendText (msg);//Send Message}} catch (IOException e) {//if this Clien                  T is not in line connections.remove (client);                  try {client.session.close (); } catch (IOException E1) {//Ignore}}}}


Java implementation of 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.