使用场景: 聊天室;大量数据常驻交互; 技术栈: Node.js, Vue.js || 原生JS 服务端代码: const app = require(‘http‘ ).createServer()const io = require(‘socket.io‘ )(app)app.listen( 8877 )io.on( ‘connection‘
使用场景: 聊天室;大量数据常驻交互;
技术栈: 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 = 1 const t = setInterval(()=>{ i++ if(i >= 12) { clearInterval(t) } // 服务端往客户端发送消息 scoket.emit(‘news‘, { hello: ‘world‘, t: new Date().getTime() }) }, 1000) // 服务端监听客户端的消息 scoket.on(‘receiveEvent‘, data => { console.log(‘receiveEvent: ‘, data) }) })
客户端代码:
-- Vue 例子:
<template> <div> <p @click="clientToServer">scoket:</p> <p v-for="(item,index) in arr" :key="index">{{item}}</p> </div> </template> <script> import io from ‘socket.io-client‘ export default { 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‘) } } </script>
-- 原生代码示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Socket Demo</title> </head> <body> <button>Send Msg</button> </body> <script src="http://img.558idc.com/uploadfile/allimg/210616/1TKG147-0.jpg"></script> <script> const wsUrl = "http://localhost:8877"; window.onload = () => { 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!‘) } }; </script> </html>
后话(备注):
这里是使用的 Node.js socket.io 第三方库, 笔者尝试过 pm2 集群部署后, 因为多核心运行的特点, 导致socket会话的id出现错误, 一直没处理好, 如有大神做过类似处理, 请交流指教!!!