<script src="vue.js"></script>
<script>
new Vue({
el: ".container",
mounted: function () {
this.nickName = prompt("input your name")
this.ws = new WebSocket("ws://localhost:3000")
this.ws.onopen = function () {
console.log("連接成功")
}
var _this = this
this.ws.onmessage = function (ev) {
var item = JSON.parse(ev.data)
_this.chatList.push(item)
}
},
data: {
ws: null,
nickName: "",
chatList: [],
content: ""
},
methods: {
send() {
var data = {
nickName: this.nickName,
content: this.content
}
//將信息發(fā)送到后端
this.ws.send(JSON.stringify(data))
}
}
})
</script>
后端
//引入ws模塊
var webSocket = require('ws')
var wss = new webSocket.Server({port:3000})
//監(jiān)聽客戶端的連接事件
wss.on("connection",function(ws){
console.log("新用戶連接")
//接收前端的信息
ws.on("message",function(data){
wss.clients.forEach(function(client){
//將信息廣播
client.send(data)
})
})
})
console.log("websocket server is running")