Websocket(3)--实时推送

来源:互联网 发布:数据山东吧 编辑:程序博客网 时间:2024/05/20 23:05

我们知道websocket的一个优势就是后台可以主动给前台推送数据,这里做个小例子演示一下。
场景:后台获取cpu数值推送到前台图表显示(这里的cpu数据是模拟的,不是真实获取)
前台数据展示图表用到echart,这里不做详细介绍,如有问题可留言。
客户端:cpu.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><script language="javascript" type="text/javascript"    src="../echarts/echarts.js"></script><script type="text/javascript" src="cpu.js"></script><title>Insert title here</title></head><body onload="page_onload_1()"><div id="main" style="height:600px;width:800px;padding:10px;"></body></html>

cpu.js

var myChart;function page_onload_1(){    drawChart();    sendReq();}function drawChart(){    //路径配置    require.config({        paths: {            echarts: '../echarts'        }    });     var option = {            title : {                text: 'cpu使用率'            },            tooltip : {                trigger: 'axis'            },            legend: {                data:['cpu使用率']            },            toolbox: {                show : true,                feature : {                    mark : {show: true},                    dataView : {show: true, readOnly: false},                    magicType : {show: true, type: ['line', 'bar']},                    restore : {show: true},                    saveAsImage : {show: true}                }            },            dataZoom : {                show : false,                start : 0,                end : 100            },            xAxis : [                {                    type : 'category',                    boundaryGap : true,                    data : [0,0,0,0,0,0]                }            ],            yAxis : [                {                    type : 'value',                    scale: true,                    name : 'cpu使用率',                    //boundaryGap: [0.2, 0.2],                    splitNumber :'10',                     min:0,                     max:100                }            ],            series : [                {                    name:'CPU使用率',                    type:'line',                    data:[0,0,0,0,0,0]                }            ]        };    require(            [                'echarts',                'echarts/chart/bar',                'echarts/chart/line'            ],                             function (ec) {                        myChart = ec.init(document.getElementById('main'));                        myChart.setOption(option);                                   }                   );    }function sendReq(){    var data;    try {        var ws = new WebSocket("ws://127.0.0.1:8080/testProject2/websocket");//连接服务器        ws.onopen = function(event){            alert("已经与服务器建立了连接rn当前连接状态:"+this.readyState);            ws.send("hello");        };        ws.onmessage = function(event){            //alert("接收到服务器发送的数据:rn"+event.data);            data = event.data.split(",");             // 动态数据接口 addData            myChart.addData([                [                    0,        // 系列索引                    data[1], // 新增数据                    true,     // 新增数据是否从队列头部插入                    false,     // 是否增加队列长度,false则自定删除原有数据,队头插入删队尾,队尾插入删队头                    data[0]                 ]            ]);        };        ws.onclose = function(event){            alert("已经与服务器断开连接rn当前连接状态:"+this.readyState);            };        ws.onerror = function(event){            alert("WebSocket异常!");            };        } catch (ex) {        alert(ex.message);        }}

此处的url中的/websocket与服务端代码注释中的@ServerEndpoint(“/websocket”)对应
服务端代码:WebSocketServer.js

package com.css.sword.websocket;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;/** * <p>Title:WebSocketServer</p> * <p>Description: </p>  * @author yuanxj * @date 2016-1-8 */@ServerEndpoint("/websocket")public class WebSocketServer {    @OnOpen    public void open(Session session){    System.out.println("已建立连接!");       }    @OnClose    public void close(Session session){    System.out.println("已关闭连接!");       }    @OnMessage    public void onMessage(Session session,String message) throws IOException, InterruptedException{        System.out.println("开始接收消息:"+message);        String result;        int i=0;        SimpleDateFormat f=new SimpleDateFormat("HH:mm:ss");//日期限制为14位        String time;        while(i<10000)        {            time = f.format(new Date());            result=time+","+String.valueOf(gengrateCpuData());            Thread.sleep(1000);            session.getBasicRemote().sendText(result);             i++;        }    }    private int gengrateCpuData()    {        int result = 0;        Random random = new Random();        for(int i = 0; i < 100;i++) {            result=Math.abs(random.nextInt())%10;            System.out.println(result);        }        return result;    }}

结果如下图所示,这里是截图,折线图是实时更新的:
这里写图片描述

0 0
原创粉丝点击