加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
server.js 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
yuhenabc 提交于 2020-06-13 12:09 . add comments
const WebSocket = require('ws');
const http = require('http');
const express = require('express');
const path = require('path');
const reducers = require('./reducers');
const app = express();
app.use(express.static(path.join(__dirname, '/public')));
const server = http.createServer(app);
const wss = new WebSocket.Server({server: server});
wss.on('connection', function (ws) {
// stage1: start
console.log('start service for a client');
for (let key in reducers) {
if(reducers.hasOwnProperty(key)) {
const start = reducers[key]['start'];
start && start(ws);
}
}
// stage2: message
ws.on('message', function (message) {
try {
const req = JSON.parse(message);
console.log(req);
for (let key in reducers) {
if(reducers.hasOwnProperty(key)) {
const message = reducers[key]['message'];
message && message(req, ws);
}
}
} catch (e) {
console.log('there is a unknow message');
}
});
// stage3: close
ws.on('close', function () {
console.log('stop service for a client');
});
});
server.listen(8000, function listening() {
console.log('Listening on %d', server.address().port);
});
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化