WebSocket+Node.js+dGram+Vue 入门级小系统

接了个基于UDP信号的实时可视化WebGIS系统项目,框架先搭起来:

一  udp和dgram

npm安装下面两个包:

const StringDecoder = require('string_decoder').StringDecoder;
const dgram = require('dgram');

主要接收代码如下:

var serverSocket = dgram.createSocket('udp4');
const decoder = new StringDecoder('utf8');
var ori_msg=''
var decode_msg=''

serverSocket.on('message', function(msg, rinfo){
    // decoder.write(Buffer.from([0xe4, 0xbd, 0xa0]));
    decode_msg=decoder.write(Buffer.from(msg))
    ori_msg=msg
    console.log(msg.length)
    console.log(msg)
//   serverSocket.send(msg, 0, msg.length, rinfo.port, rinfo.address);
});
serverSocket.on('error', function(err){
    console.log(err)
});
serverSocket.on('listening', function(){
    // console.log(err)
})
serverSocket.bind(6000)

打开对应端口号的udp发送端,可以接收到udp字节流数据

二 WebSocket

npm安装这个包

const WebSocketServer = require('ws').Server

这里设置了一个全局变量,随时间递增,WebSocket后台将此变量和从udp接收到的字节流一同推送到前台,由于系统不需要向后台推送数据的功能,因此后台没有接收数据的事件.后台代码如下:

var msg=0
setInterval(add,1000)//每隔5秒 服务端向浏览器 推送消息

var wss = new WebSocketServer({ port: 9000 })
wss.on('connection', function (ws) {
    console.log('client connected')
});

function add(){
    msg++
    if(this.msg>1000){
        msg=0
    }
    wss.clients.forEach(function each(client) {
        client.send(msg+'\n'+ori_msg);
    });
}

三 Vue

Vue脚手架等等略过,这里用到的Vue,此处贴上主Vue页面的代码

<template>
    <h1>{{ msg }}</h1>
</template>
<script>
// import io from 'socket.io'
// import vue from 'vue'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: '还没收到'
    }
  },
  methods: {
    change_msg (value) {
      this.msg = value
    },
    http_test () {
      this.$http.get(
        'http://localhost:8081/back'
      ).then(res => {
        this.msg = res
      })
    }
  },
  mounted: function () {
    var that = this
    if (window.WebSocket) {
      console.log('支持')
    } else {
      console.log('不支持')
    }
    var ws = new WebSocket('ws://localhost:9000')
    ws.onopen = function () {
      console.log('open')
      ws.send('hello')
    }
    ws.onmessage = function (evt) {
      that.change_msg(evt.data)
      console.log(evt.data)
    }
    ws.onclose = function (evt) {
      console.log('WebSocketClosed!')
    }
    ws.onerror = function (evt) {
      console.log('WebSocketError!')
    }
  }
}
</script>
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

四 效果

执行后台页面代码,开启后台服务

执行 npm run dev开启前台服务

在浏览器中输入前台对应网址,效果如下:

 

 由前面的数字可以看出实时推送的效果,因为udp收到的是我们自己定义格式的字节流,在这里没有解译出来的必要,所以出现了后面的乱码.至此框架算是跑起来了,欢迎各位多提意见,一同进步!

猜你喜欢

转载自www.cnblogs.com/majaiyou/p/10337290.html
今日推荐