服務(wù)端
首先新創(chuàng)建一個node的空項目,然后安裝 npm install nodejs-websocket
在index.js里面編寫下面的內(nèi)容:
var ws = require("nodejs-websocket");
console.log("開始建立連接...")
var server = ws.createServer(function(conn){
conn.on("text", function (str) {
console.log("收到的信息為:"+str)
conn.sendText(str)
})
conn.on("close", function (code, reason) {
console.log("關(guān)閉連接")
});
conn.on("error", function (code, reason) {
console.log("異常關(guān)閉")
});
}).listen(8001)
console.log("WebSocket建立完畢")
上面只是服務(wù)端跑起來一個webstock拴孤,為了方便后面的測試和演示,收到什么內(nèi)容就回復(fù)什么內(nèi)容
客戶端
新建一個vue項目,在vue項目的入口文件 main.js編寫以下內(nèi)容
import Vue from 'vue'
import App from './App'
import {router} from './router/index'; //引入路由實例
import {webstock} from './libs/webstock'
Vue.prototype.$webstock = webstock;
Vue.prototype.$eventHub=new Vue(); //注意這里的寫法
export const VueObj= new Vue({
router,
render: h => h(App)
}).$mount('#app-box')
webstock.js:
import {VueObj} from '../main'
export const webstock = new WebSocket("ws://192.168.1.119:8001");
/**
* webstock連接成功
*/
webstock.onopen = function () {
console.log("websocket open");
/* let obj = {"requestType": "login"}
webstock.send(JSON.stringify(obj))*/
}
/**
* webstock接收消息
*/
webstock.onmessage = function (message) {
//console.log(JSON.parse(message.data));
//這里注冊了一個A事件
VueObj.$eventHub.$emit('A事件', JSON.parse(message.data))
}
/**
* webstock關(guān)閉
*/
webstock.onclose = function (event) {
console.log("websocket close");
}
/**
* webstock出錯
*/
webstock.onerror = function (event) {
webstock.close(event);
console.log("websocket error");
}
./router/index (定義路由路徑)
{path: '/test', component: () => import('@/components/Test/test')},
test.vue
<template>
<div>
<p><input type="text" v-model="webstock_type"><button @click="sendMsg">測試webstock</button></p>
</div>
</template>
<script>
export default {
data() {
return {
webstock_type:'A'
}
},
created() {
//監(jiān)聽A事件理疙,如果只想監(jiān)聽一次可以用 $this.$eventHub.$once
this.$eventHub.$on('A事件', (res)=>{
console.log('test.vue界面收到消息---',res);
} )
},
beforeDestroy(){
//如果組件沒有緩存赃梧,記得離開組件前解除A事件的監(jiān)聽焕济,
//不然重新加載該組件會出現(xiàn)重復(fù)監(jiān)聽的情況,緩存組件可以用 <keep-alive>
this.$eventHub.$off('A事件')
console.log(123);
},
methods: {
sendMsg:function () {
//往服務(wù)端發(fā)送一個消息晴弃,服務(wù)端馬上回復(fù)消息骗露,從觸發(fā)webstock的接收消息方法里面注冊的A事件
this.$webstock.send(JSON.stringify(this.webstock_type))
}
}
}
</script>