openlayers学习二--利用websocket接收udp数据在地图上画点

1.在openlayers上画点

先新建一个vector矢量层,写上渲染模式,再把vector层加入到map中

    
var source = new ol.source.Vector();
    var vectorLayer = new ol.layer.Vector({
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(255,255,255,0.2)'
        }),
        stroke: new ol.style.Stroke({
          color: '#ffcc33',
          width: 2
        }),
        image: new ol.style.Circle({
          radius:3,
          fill: new ol.style.Fill({
            color: '#ffcc33'
          })
        })
      })
    });
    map.addLayer(vectorLayer);

写一个画点函数,就是来一个点就将点坐标设置为feature,并加入到矢量层,这里传入一个时间变量,以备udp包传入的参数。

    var drawPoint = function(time){
      var coord = ol.proj.transform([lon+3*Math.cos(time),lat+3*Math.sin(time)],'EPSG:4326', 'EPSG:3857');
      var feature = new ol.Feature({
        geometry: new ol.geom.Point(coord)
      });
      lon -=0.001;
      i++;
      vectorLayer.getSource().addFeature(feature);
    }

2.利用node.js处理udp包

先创建udpsocket,绑定端口,并处理包数据,这里处理的是小端float数据。

const dgram = require('dgram');
let server = dgram.createSocket('udp4');
server.bind(6000);

var pp = [];
server.on('message',function(msg,rinfo){
    const t = msg.slice(0,4);
    const b = msg.slice(4,8);
    const l = msg.slice(8,12);

    const p = new Array(3);
    p[0] = t.readFloatLE(0).toString();
    p[1] = b.readFloatLE(0).toString();
    p[2] = l.readFloatLE(0).toString();
    pp = p;
    console.log(pp.toString());
})

3. 利用node.js发送数据

创建websocket,监听3000端口,并将udp数据发送出去

var time = 1;
var ws = require('nodejs-websocket');
var wss = ws.createServer(conn =>{
    console.log("正在连接");
    conn.on('text',function(data){
        //console.log("收到:"+data);
        conn.send(pp.toString());
        time+=1;
    })
    conn.on('close',function(){
        conn.log('closed');
    })
    conn.on('error',function(){
        conn.log('error');
    })
})

wss.listen(3000,function(){
    console.log('正在监听3000端口');
})

4.在网页中利用websocket收数

监听3000端口,10hz发送hello,收到数据时,解包得到时间,并传入drawPoint函数

    const ws = new WebSocket('ws://localhost:3000');
    ws.onopen = function(e){
      console.log('连接成功');
      setInterval(function(){
        ws.send('hello');
      },100)
    }
    ws.onmessage = function(e){
      var pp = (e.data).split(",");
      drawPoint(parseInt(pp[0]));
      console.log(pp[0]);
    };

5.写一个c++发包程序,测一下

 

完活

posted @ 2022-01-16 10:01  fkess  阅读(322)  评论(0)    收藏  举报