WebSocket and websocket

Source: Internet
Author: User

WebSocket and websocket

1. What is webSocket?

As we all know, the browser supports stateless http. When a user sends a request on the browser side, the server returns a response. This kind of response can be sent only when the user requests continuously. Before html5, to implement a real-time service data retrieval function, you may only need to use the round-robin method to send a request each time to obtain the server response data. When html5 comes, it brings a convenient technology webSocket. Unlike http requests, each time you want to obtain data, a connection is established, and the connection is closed after obtaining the data. WebSocket only establishes a persistent connection with the client once. In each activity in the future, you no longer need to establish a connection with the traffic manager client, which improves the efficiency of such frequent requests.

II. Application of webSocket in projects

There is a need for a recent project to obtain the Real-Time Current Value of the power supply device and display it in a visual line chart. Based on this business demand, I used webSocket to implement this function. I don't need to talk much about it, so I can directly paste the dry goods!

(1) Prepare the background jar package required by webSocket.

Here I need to explain that the jar package conflicts with the jar package of tomcat itself. We recommend that you do not reference it in this project, but you can reference it in other projects externally.

(2) Front-end js code block

Var webScoket_url = "ws: //" + location. host + "/PowerDemo/websocket_login"; var webSocket = new WebSocket (webScoket_url); // The js client initializes the WebSocket event method function initWebSocket () {// receives the webSocket message returned by the server. onerror = function (event) {console. log ("webSocket exception", event) ;}; // This method will be called when we create a connection to the server. WebSocket. onopen = function (event) {// onOpen (event) console. log ("create connection to open", event) ;}; // receives message events. WebSocket. onmessage = function (event) {onMessage (event)}; webSocket. onclose = function (event) {console. log ("Page close", event); webSocket = null ;}} function onMessage (event) {// document. getElementById ('messages '). innerHTML + = event. data + '<br/>'; // console. log (event + "=" + event. data); commonService. publishNotify ("getMessageEvent", event. data );}
View Code
/*** WebSocket. readyState status value CONNECTING 0 connection is not enabled yet. OPEN 1 connection is enabled and ready for communication. The CLOSING 2 connection is being closed. The CLOSED 3 connection is CLOSED, or the connection cannot be established. */Vm. testScoket = function (obj) {var json_str = {"type": obj. NUMPLATE}; if (webSocket = null) {webSocket = new WebSocket (webScoket_url); $ timeout (function () {initWebSocket (); if (webSocket. readyState = 1) {webSocket. send (JSON. stringify (json_str); }}, 1000)} else if (webSocket! = Null & webSocket. readyState = 1) {initWebSocket (); webSocket. send (JSON. stringify (json_str);} else if (webSocket. readyState = 2 | webSocket. readyState = 3) {webSocket = new WebSocket (webScoket_url); $ timeout (function () {initWebSocket (); if (webSocket. readyState = 1) {webSocket. send (JSON. stringify (json_str) ;}, 1000)} // QuestionService. initModal ("views/power/failure/msgModal.html", "ModalController", null );}
View Code

(3) backend webSocket

Package com. zdwl. scoket; import java. io. IOException; import java. util. date; import javax. websocket. onClose; import javax. websocket. onMessage; import javax. websocket. onOpen; import javax. websocket. session; import javax. websocket. server. serverEndpoint; import net. sf. json. JSONObject; import net. sf. json. jsonConfig; import org. springframework. context. annotation. configuration; import org. springframework. web. servlet. Config. annotation. enableWebMvc; import com. zdwl. comm. jqgridPage; import com. zdwl. comm. util. jsonDateValueProcessor; import com. zdwl. comm. util. springUtil; import com. zdwl. model. vo. power. powerEvent; import com. zdwl. service. power. powerEventQueryServiceImpl; @ Configuration @ EnableWebMvc @ ServerEndpoint (value = "/websocket") public class BusPowerWebScoket extends SpringUtil {@ OnMessage public void onMessage (St Ring message, Session session) throws IOException, InterruptedException {PowerEventQueryServiceImpl eventQueryService = (PowerEventQueryServiceImpl) super. getBean ("powerEventQueryService"); // receives the front-end web message System. out. println ("receive:" + message); JSONObject jo = null; try {jo = new JSONObject (). fromObject (message); System. out. println ("=" + jo. get ("rows") + "====" + jo. toString (); PowerEvent event = new Power Event (); String beginTime = jo. get ("beginDate") + ""; String date = null; // shoveFrontSecondForGetDate (5*60); event. setBeginDate (date); JqgridPage = new JqgridPage (); String pageSize = jo. get ("rows") + ""; String curPageNo = jo. get ("page") + ""; if (curPageNo! = Null) {page. setCurPageNo (new Integer (curPageNo);} if (pageSize! = Null) {page. setPageSize (new Integer (pageSize);} int sentMessages = 0; while (true) {Thread. sleep (3000); eventQueryService. queryRealTimeCurrentInfo (page, event, null); JsonConfig jsonConfig = new JsonConfig (); jsonConfig. registerJsonValueProcessor (Date. class, new JsonDateValueProcessor (); JSONObject json = JSONObject. fromObject (page, jsonConfig); String str = json. toString (); // send the session of the text message. ge TBasicRemote (). sendText (str); sentMessages ++ ;}} catch (Exception e) {e. printStackTrace () ;}@ OnOpen public void onOpen () {System. out. println ("client link... ") ;}@ OnClose public void onClose () {System. out. println (" link closed .... ");}/* Public static void main (String [] args) {shoveFrontSecondForGetDate (120);} * // * public static String shoveFrontSecondForGetDate (int secs) {Date date = new Date (); Long ll = date. getTime ()-secs * 1000L; SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); // System. out. println ("current time:" + sdf. format (date); date = new Date (ll); System. out. println ("push before" + secs + "seconds:" + sdf. format (date); return sdf. format (date );}*/}
View Code

 

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.