实现websocket主要是两点,一个是协议的升级,再者就是数据包的解析与封装。
目前比较火的websocket框架有socket.io 和 ws
socket.io http://socket.io:43.5k star
实际上不是一个 WebSocket 库,而是一个实时 pub/sub 框架。简单地说,Socket.io 是包含 WebSocket 功能的一个框架,如果要使用该库作为 server 端的服务,则 client 也必须使用该库,因为它不是标准的 WebSocket 协议,而是基于 WebSocket 再包装的消息通信协议。
websockets/ws:9k star
强大易用的 websocket 服务端、客户端实现,还有提供很多强大的特性,最后选择 WS。
客户端代码:
<input type="text" name="msg"> <button type="button" onclick="send()">发送</button> <script> var socket = new WebSocket("ws://127.0.0.1:8080"); var stringData = "Hello 世界!"; socket.onopen = function(){ console.log("open"); socket.send(stringData); } socket.onerror = function(err){ console.log("error: ", err); } socket.onclose = function(){ console.log('close'); } socket.onmessage = function(event){ var data = event.data; console.log("收到服务器发来数据:", data); socket.send("收到服务器发来数据:" + data); } function send(){ var msg = document.querySelector("input[name='msg']").value; socket.send(msg); } </script>
服务器端:
var WebSocket = require('ws'); // var { WebSocketServer } = require('ws'); var WebSocketServer = WebSocket.WebSocketServer; const wss = new WebSocketServer({ port: 8080, perMessageDeflate: { zlibDeflateOptions: { // See zlib defaults. chunkSize: 1024, memLevel: 7, level: 3 }, zlibInflateOptions: { chunkSize: 10 * 1024 }, // Other options settable: clientNoContextTakeover: true, // Defaults to negotiated value. serverNoContextTakeover: true, // Defaults to negotiated value. serverMaxWindowBits: 10, // Defaults to negotiated value. // Below options specified as default values. concurrencyLimit: 10, // Limits zlib concurrency for perf. threshold: 1024 // Size (in bytes) below which messages // should not be compressed if context takeover is disabled. } }); wss.on('connection', function connection(ws) { console.log("websocket 链接中。。。"); ws.on('open', function open() { console.log("websocket 创建成功。。。"); ws.send('something'); }); ws.on('message', function message(data) { console.log('received: %s', data); }); setInterval(function () { ws.send('你好,客户端!当前服务器时间是:' + Date()); }, 1000); }); wss.on('error', function (event) { console.log("错误信息:", event); });
参考:
https://www.zhihu.com/question/37647173/answer/1403359896
https://www.ruanyifeng.com/blog/2017/05/websocket.html
socket 网络协议 RFC6455
修改时间 2022-05-31
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。