Vue2、websocket 与node.js接口 本地测试

Vue2、websocket 与node.js接口 本地测试

1.  安装vue-native-websocket模块
2.  yarn add vue-native-websocket 
或者用 
npm install vue-native-websocket --save
 

3. 在main.js中引入websocket

import websocket from ‘vue-native-websocket‘

Vue.prototype.$websocket = websocket

Vue.use(websocket,‘ws://localhost:3000‘,{

  reconnection: true,// (Boolean) whether to reconnect automatically (false)

  reconnectionAttempts: 5,// (Number) number of reconnection attempts before giving up (Infinity),

  reconnectionDelay: 3000,// (Number) how long to initially wait before attempting a new (1000)

})

 

 

项目中main.js使用如下图

 

分享图片

 

4.在项目中新建websocket.vue文件,在HelloWorld.vue中引入

 

分享图片

 

5. HelloWorld.vue文件代码如下

 

<template>

  <div class="hello">

   <websocket/>

  </div>

</template>

 

<script>

import websocket from "@/components/websocket"

export default {

  name: ‘HelloWorld‘,

  components:{

    websocket

  },

  data () {

    return {

    

    }

  },

</script>

 

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>

 

</style>

 

6.websocket.vue代码如下

<template>

    <div>

        {{msg}}

    </div>

</template>

 

<script>

    export default {

        name:"websocket",

        data() {

            return {

                websock: null,

                msg:""

            }

        },

 

    created(){

           //页面刚进入时开启长连接

            this.initWebSocket()

       },

    destroyed: function() {

    //页面销毁时关闭长连接

      this.websocketclose();

 

    },

 

    methods: {

 

      initWebSocket(){ //初始化weosocket

       

        const wsuri = ‘ws://localhost:3000‘;//ws地址

 

        this.$websocket = new WebSocket(wsuri);

 

        this.$websocket.onopen = this.websocketonopen;

 

        this.$websocket.onerror = this.websocketonerror;

 

        this.$websocket.onmessage = this.websocketonmessage;

 

        this.$websocket.onclose = this.websocketclose;

       },

 

      websocketonopen() {

        console.log("WebSocket连接成功");

      },

 

      websocketonerror(e) { //错误

        console.log("WebSocket连接发生错误");

      },

 

      websocketonmessage(e){ //数据接收

        console.log(e);

this.msg=e.data

      },

 

      websocketsend(agentData){//数据发送

        this.$websocket.send(agentData);

      },

 

      websocketclose(e){ //关闭

        console.log("connection closed (" + e.code + ")");

     },

   },

  }

 </script>

 

7.创建一个新的项目,新建1.js文件,用于写node.js接口,安装

nodejs-websocket模块npm install websocket

用cmd或者git bash进入后台接口文件,1.js,然后命令行输入node 1.js,启动后台服务。文件如下:

var WebSocketServer = require(‘websocket‘).server;

var http = require(‘http‘);

 

var server = http.createServer(function(request,response) {

    console.log((new Date()) + ‘ Received request for ‘ + request.url);

    response.writeHead(404);

    response.end();

});

server.listen(3000,function() {

    console.log((new Date()) + ‘ Server is listening on port 3000‘);

});

 

wsServer = new WebSocketServer({

    httpServer: server,

 

});

 

 

wsServer.on(‘request‘,function(request) {

    //当前的连接

    var connection = request.accept(null,request.origin);

 

    setInterval(function(){

        connection.sendUTF(‘服务端发送消息‘ + (Math.random().toFixed(2)))

    },500)

 

    console.log((new Date()) + ‘已经建立连接‘);

    connection.on(‘message‘,function(message) {

        if (message.type === ‘utf8‘) {

            console.log(‘Received Message: ‘ + message.utf8Data);

            connection.sendUTF(message.utf8Data);

        }

        else if (message.type === ‘binary‘) {

            console.log(‘Received Binary Message of ‘ + message.binaryData.length + ‘ bytes‘);

            connection.sendBytes(message.binaryData);

        }

    });

    connection.on(‘close‘,function(reasonCode,description) {

        console.log((new Date()) + ‘ Peer ‘ + connection.remoteAddress + ‘断开连接‘);

    });

});                                          

 

8. Vue2、websocket 与node.js接口 本地测试到这里就结束了,以上代码用到Websocketd的方法详见websocket文档

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...