nodejs websocket server
安裝:
npm install ws
npm install ws –save // 安裝到工程目錄
API使用:
const express = require(‘express‘); const http = require(‘http‘); const url = require(‘url‘); const WebSocket = require(‘ws‘);
const app = express();
/** * WebSocket服務端例子 * 框架:https://github.com/websockets/ws */ app.use(function (req, res) { res.send({msg: "hello"}); });
const server = http.createServer(app); //noinspection JSAnnotator const wss = new WebSocket.Server({server});
function testWebSocketServerApi() { wss.on(‘connection‘, function connection(ws, req) { const location = url.parse(req.url, true); const ip = req.connection.remoteAddress; const port = req.connection.remotePort; console.log(ip + " " + port);
ws.on(‘message‘, function incoming(message) { console.log(‘received: %s‘, message); });
ws.on(‘close‘, function (params) { console.log(‘params: %s‘, message); });
ws.send(‘something‘); });
server.listen(8080, function listening() { console.log(‘WebSocket Listening on %d‘, server.address().port); });
const WSS = new WebSocket.Server({ port: 8081 });
WSS.on(‘connection‘, function connection(ws) { ws.on(‘message‘, function incoming(message) { console.log(‘received: %s‘, message); });
ws.send(‘something‘); }); } |
參考:
websockets/ws
nodejs websocket server