文章目录
[websocket](WebSocket - Web API 接口参考 | MDN (mozilla.org))
简单的来说,websocket是用来实现客户端和服务端进行双向连接的,连接之后,服务器可以给客户端主动发数据
前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script> let websocket = null; window.onload = function () { // console.log(window) // 检测当前浏览器是否支持websocket if ("WebSocket" in window) { websocket = new WebSocket("ws://127.0.0.1:3000"); // 监听ws连接 websocket.onopen = (e) => { console.log("websocket is connection", e); }; // 当ws收到消息之后触发回调 websocket.onmessage = (e) => { console.log("message被触发", e); }; // 监听ws关闭事件 websocket.onclose = (e) => { console.log("websocket is closed\r\n", e); }; // 监听ws错误事件 websocket.onerror = (e) => { console.log("websocket is error\r\n", e); }; }else{ console.error("您的浏览器不支持websocket,请更换浏览器再试") } }; function send() { console.info("我要发消息拉"); websocket.send("hello"); } </script> </head> <body> <button onClick="send()">发送消息</button> </body> </html>
后端
- 使用
node
依赖node-websocket实现
"use strict"; const ws = require('nodejs-websocket') const server = ws.createServer(function(con){ console.log("new connection") // 收到前端发来的消息 con.on('text', str=>{ console.log('receiving \r\n', str) con.sendText('收到'+str+'!!!!') // console.log(server.connections) }) setInterval(()=>{ // 给前端发送消息 send() },3000) // 监听所有的ws断开 con.on('close', (code,reason)=>{ console.log('connection is closed\r\n',code, reason) }) con.on("error",e=>{ console.log("error=\r\n",e) }) }) /** * 利用自定义的方法, * 对server的所有链接遍历广播消息,避免单一链接断开后, * 服务端继续发消息,造成4077持续错误 */ function send(){ // server.connections 是当前已连接的所有前端服务 server.connections.forEach(connection=>{ connection.sendText('hahah') }) } // 启动服务 server.listen(3000,()=>{ console.info('ws is running at:\r\n ws://127.0.0.1:3000') })
socket.io
优点:可以利用http进行websocket通信,可以自定义事件分发
前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.bootcdn.net/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script> <script> let socket = null window.onload = function(){ socket = io('http://127.0.0.1:3000') // console.log(socket) socket.on('connect',()=>{ console.log("成功链接服务端啦") }) socket.on('disconnect',()=>{ console.log("服务断开,尝试重新链接") socket.connect() }) socket.on('msg',(data)=>{ console.log('收到msg',data) }) } function send(){ if( !socket ) { console.error("还没有链接") }else{ console.log("开始发数据") socket.emit('text','客户端发来数据') } } function hello(){ if(!socket){ console.error("还没有链接") }else{ console.log("发送hello事件") socket.emit('hello','world') // 触发hello事件带world参数 } } </script> </head> <body> <button onclick='send()'>发送消息</button> <button onclick='hello()'>hello</button> </body> </html>
后端
const server = require('http').createServer(); const io = require('socket.io')(server, { cors: true }); io.on('connection', client => { console.log("有人链接了\r\n") // client.on 监听客户端emit事件 client.on('event', data => { console.log('event\r\n', data) }); client.on('disconnect', () => { console.log('client is disconnected\r\n') }); client.on('hello',(data)=>{ console.log("hello事件被触发,收到数据",data) }) client.on('text',(data)=>{ console.log('text事件被触发',data) }) // setInterval(()=>{ // console.log('开始发信息') // client.emit('msg',"我是服务端发来的数据") // }, 10000) }); server.listen(3000); /** * @todo * 因为使用小程序 socket.io 4监听不到所以回退到2 */
- [github地址](csDeng/websocket_node: websocket学习 (github.com))