分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

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

发布时间:2023-09-06 02:32责任编辑:沈小雨关键词:jsWebNode

接了个基于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=0setInterval(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收到的是我们自己定义格式的字节流,在这里没有解译出来的必要,所以出现了后面的乱码.至此框架算是跑起来了,欢迎各位多提意见,一同进步!

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

原文地址:https://www.cnblogs.com/majaiyou/p/10337290.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved