前期必备环境:
node和vue
- 首先你要知道ws(webSocket,文章后均简称ws或wss,就像http和https一样,这两个是weSocket中的两种协议标识)是什么,干嘛用的:
开发中会遇到一种情况就是:
前端页面要根据后台数据实时更新,最简单的办法就是,每过一段时间向后台发送请求查看数据是否更新。这样很浪费资源,而且也不能保证实时更新。所以,ws就是解决这个问题的 - ws是一个长连接,它的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息
- 可以发送文本,也可以发送二进制数据......
好了不说了,文末有参考文章链接;上代码
这里有一个websocket体验链接,来自阮大神
前端工作(以下代码复制即用)
1.首先创建一个vue项目装上vue-native-websocket,npm上也有教你怎么用,可以看看。
yarn add vue-native-websocket
# or
npm install vue-native-websocket --save
<!--main.js-->
import Vue from 'vue'
import App from './App.vue'
import websocket from 'vue-native-websocket'
Vue.use(websocket, 'ws://10.8.10.103:9090', {// 这里要填的是服务器的地址,可以换一个在线服务器wss://echo.websocket.org
reconnection: true, // (Boolean)是否自动重连,默认false
reconnectionAttempts: 5, // 重连次数
reconnectionDelay: 3000, // 再次重连等待时常(1000)
})
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
然后在你要用到ws的页面,组件上用上他

<!--hello world-->
<template>
<div class="hello">
<h1>{{msg}}</h1>
<section class="center">
<div class="message">{{msg}}</div>
<div class="input">
<textarea name id="text" cols="30" rows="2" v-model.trim="text"></textarea>
<button class="danger" @click="clear">clear</button>
<button class="green" :disabled="empty" @click="websocketsend">send</button>
</div>
</section>
</div>
</template>
<script>
export default {
name: "websocket",
data() {
return {
msg:'',
text: "",
empty: true,
send:true,
};
},
watch: {
text: function(newValue, oldValue) {
newValue.length > 0 ? (this.empty = false) : (this.empty = true);
}
},
methods: {
clear() {
this.text = "";
this.$socket.close()
},
initWebSocket() {
//初始化weosocket,这些onopen是一个事件,当
this.$socket.onopen = this.websocketonopen;
this.$socket.onerror = this.websocketonerror;
this.$socket.onmessage = this.websocketonmessage;
this.$socket.onclose = this.websocketclose;
},
websocketonopen(e) {
// 链接ws服务器,e.target.readyState = 0/1/2/3
//0 CONNECTING ,1 OPEN, 2 CLOSING, 3 CLOSED
console.log("WebSocket连接成功",e);
},
websocketonerror(e) {
//错误
console.log("WebSocket连接发生错误");
},
websocketonmessage(e) {
//数据接收
console.log(JSON.parse(e.data))
this.msg = 'hello world';
},
websocketsend(e) {
//数据发送
this.$socket.send(JSON.stringify({test:'www.baidu.com'}));
// this.$socket.close(1000)
console.log(this.$socket.readyState)// 当前链接状态 https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket#%E5%B8%B8%E9%87%8F
},
websocketclose(e) {
//关闭链接时触发
var code = e.code;// 状态码表 https://developer.mozilla.org/zh-CN/docs/Web/API/CloseEvent
var reason = e.reason;
var wasClean = e.wasClean;
console.log(code,reason,wasClean);
}
},
created() {
this.initWebSocket();
},
destoryed() {
this.$socket.close();
}
</script>
后端工作
1.新建文件夹server——>server.js——>安装依赖
npm install -g nodemon
npm install ws
npm install express
<!--yarn 一样用的-->
2.简单写一下服务端
<!--server.js-->
var WebSocket = require('ws');
var wss = new WebSocket.Server({ port: 9090 });// 服务器端口
wss.on('connection', ws=>{
console.log('server: receive connection.');
ws.on('message', message=>{
console.log('server: received:',message);
});
// 处理异常
ws.on('error', error => {
console.log(error)
});
// 处理关闭
ws.on('close', closed => {
console.log(closed)
})
// 主动发送信息
ws.send(JSON.stringify(ws));
// var index=0
// setInterval(()=>{
// ws.send(`testMessage${++index}`)
// },2000)
});
#最后
前端 yarn serve
后端 nodemon server.j
看控制台输出就可以了,感兴趣就自己丰富一下页面
参考资料与启发: