webSocket 使用,websocket使用

來源:互聯網
上載者:User

webSocket 使用,websocket使用

一.什麼是webSocket?

     眾所周知,大家都知道瀏覽器支援無狀態的http協議,使用者在瀏覽器端發送一個請求,服務端返回一個響應。這種響應是基於使用者不斷的請求才能發送。在html5之前,要實現一個即時擷取業務資料的功能,或許還只能用輪詢的方式,每次去發送一個請求去擷取伺服器響應的資料。那html5到來之時,帶來了一個便利的技術 webSocket.它不像http請求那樣,每次要擷取資料,就建立一次串連,擷取完後串連就斷開。webSocket 只建立一次和用戶端的長串連,以後的每次活動,都無需再和流量器用戶端建立串連,提高了這種頻繁請求的效率。

二.webSocket 在項目中的運用

   最近項目上有個需求,要擷取電源裝置的即時電流值,並以可視化的折線圖展示出來。基於這塊業務需求,我用webSocket實現了該功能,廢話不多說了,直接貼上乾貨!

  (1)準備webSocket所需的後台jar包。

     這裡我需要說明下,該jar包與 tomcat 自身的jar有衝突,建議不要在本項目內引用,可外置放在其他項目中引用過來。

  (2)前端js代碼塊

var webScoket_url = "ws://"+location.host+"/PowerDemo/websocket_login";            var webSocket = new WebSocket(webScoket_url);            //js 用戶端初始化WebSocket自身事件方法            function initWebSocket(){                //接受服務端返回的訊息                webSocket.onerror = function(event) {                  console.log("webSocket異常",event);                };                                  //我們建立一個串連到伺服器的串連時將會調用此方法。                webSocket.onopen = function(event) {                  //onOpen(event)                  console.log("建立串連開啟",event);                };                                  //接收訊息事件。                webSocket.onmessage = function(event) {                  onMessage(event)                };                                webSocket.onclose = function(event){                    console.log("頁面的關閉",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 狀態值                CONNECTING    0    串連還沒開啟。                OPEN    1    串連已開啟並準備好進行通訊。                CLOSING    2    串連正在關閉的過程中。                CLOSED    3    串連已經關閉,或者串連無法建立。              */             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)背景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(String message, Session session)        throws IOException, InterruptedException {        PowerEventQueryServiceImpl eventQueryService=(PowerEventQueryServiceImpl)super.getBean("powerEventQueryService");        //接受前端的web 訊息        System.out.println("接收: " + message);        JSONObject jo=null;        try {            jo = new  JSONObject().fromObject(message);            System.out.println("==="+jo.get("rows")+"======"+jo.toString());            PowerEvent event=new PowerEvent();            String beginTime =jo.get("beginDate")+"";            String date = null;//shoveFrontSecondForGetDate(5*60);            event.setBeginDate(date);            JqgridPage page = 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();              //發送簡訊              session.getBasicRemote().sendText(str);              sentMessages++;            }        } catch (Exception e) {            e.printStackTrace();        }      }             @OnOpen      public void onOpen() {        System.out.println("用戶端連結。。。");      }           @OnClose      public void onClose() {        System.out.println("連結關閉。。。。");      }          /*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("目前時間:"+sdf.format(date));        date= new Date(ll);        System.out.println("推前"+secs+"秒的時間:"+sdf.format(date));        return sdf.format(date);    }*/}
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.