使用场景: 聊天室;大量数据常驻交互;
技术栈: Node.js, Vue.js || 原生JS
服务端代码:
const app = require('http').createServer()
const io= require('socket.io')(app)
app.listen(8877)
io.on('connection', scoket =>{
let i= 1const t= setInterval(()=>{
i++
if(i >= 12) {
clearInterval(t)
}//服务端往客户端发送消息
scoket.emit('news', { hello: 'world', t: newDate().getTime() })
},1000)//服务端监听客户端的消息
scoket.on('receiveEvent', data =>{
console.log('receiveEvent: ', data)
})
})
客户端代码:
-- Vue 例子:
scoket:
{{item}}
beforeMount() {//初始化 客户端 socket
this.socket = io('http://localhost:8877')
},
data() {return{
arr: []
}
},
mounted() {//监听服务端 scoket 'news' 数据流
this.socket.on('news', data =>{this.arr.push(data)
})
},
methods: {//客户端往服务端发送消息
clientToServer() {this.socket.emit('receiveEvent', 'Hi~ im from clientSide')
}
},//销毁 socket
beforeDestroy() {this.socket.close('news')
}
}
-- 原生代码示例:
Socket DemoSend Msg
window.οnlοad= () =>{
const socket=io.connect(wsUrl);//监听服务端消息
socket.on("news", data =>{
console.log("news: ", data);
});//往服务端发送消息
document.getElementsByTagName('button')[0].onclick = function() {
socket.emit('receiveEvent', 'msg from client!')
}
};
后话(备注):
这里是使用的 Node.js socket.io 第三方库, 笔者尝试过 pm2 集群部署后, 因为多核心运行的特点, 导致socket会话的id出现错误, 一直没处理好, 如有大神做过类似处理, 请交流指教!!!
原文出处:https://www.cnblogs.com/qq4535292/p/11227444.html