websocket作为不同于http的数据传输方式,是开发一些实时系统的不二选择。
最近在研究开发websocket方面的小程序。小程序客户端直接对websocket做了封装。自己只要写后端就可以了。我拿来测试的后端代码如下,本地环境下小程序可以成功运行。
let websocket = require("websocket"); let http = require("http"); const WebSocketServer = websocket.server; // 创建一个http Server let httpServer = http.createServer((request, response) => { console.log("received a request"); response.writeHead(404); response.end(); }); // 创建一个websocket Server,websocket Server需要建立在http server之上 let wsServer = new WebSocketServer({ httpServer: httpServer, autoAcceptConnections: true }); /** * 广播所有客户端消息 * @param {String} type 广播方式(admin为系统消息,user为用户消息) * @param {String} message 消息 * @param {String} nickname 用户昵称,广播方式为admin时可以不存在 */ function broadcastSend(type, message, nickname) { clients.forEach(function(v, i) { if (v.ws.readyState === ws.OPEN) { v.ws.send(JSON.stringify({ "type": type, "nickname": nickname, "message": message })); } }) } // 事件监听 wsServer.on("connect", (connection) => { let clients = []; clients.push({ ws: connection, name: 1 }) console.log(">>>come from: " + connection.remoteAddress); // 显示连接客户端的ip地址 connection.on("message", (message) => { console.log(message.type); console.log(">>>message: ", message); // 接收到信息的类型和内容,注意都是utf8编码 connection.sendUTF(message.utf8Data + '我是websocket'); // 把接收到的信息发回去 clients.forEach((v, i) => { if (v.ws.readyState === connection.OPEN) { v.ws.send(JSON.stringify({ "type": 1, "nickname": 2, "message": 3 })); } }) }); connection.on("close", (reasonCode, description) => { console.log(connection.remoteAddress + " has disconnected."); }); }); // 启动服务器 httpServer.listen(8082, () => { console.log(">>>Http Server is listening on port 8082!"); });