使用 nodejs 搭建 websocket 服务器


唔,需要提前准备好 nodejs 和 npm 的环境,然后使用下面命令安装相关依赖包:

npm install ws
npm install http
npm install url

其它也不知道说点啥,直接上代码吧:

// 代码参考自:https://github.com/websockets/ws#usage-examples

console.log("WebSocket 服务启动中...");

var http = require('http');
var WebSocket = require('ws');
var url = require('url');

var httpServer = http.createServer();
var webSocketServer = new WebSocket.Server({
    // 若不在 http 服务下独立启动 websocket 服务器,可在此设置监听端口
    // port: 8010
    // 若在 http 服务下监听请求,则将 noServer 设置为 true
    noServer: true
});

webSocketServer.on('connection', function(client) {
    client.on('message', function(message) {
        console.log('来自客户端的消息:%s', message);
        client.send('服务端接收到的消息:' + message);
    });
});

httpServer.on('upgrade', function upgrade(request, socket, head) {
    var pathname = url.parse(request.url).pathname;
    
    // websocket 的监听路径
    if (pathname === '/ws') {
        webSocketServer.handleUpgrade(request, socket, head, function done(ws) {
            webSocketServer.emit('connection', ws, request);
        });
    }
    else {
        socket.destroy();
    }
});

// http 服务的监听端口
httpServer.listen(8010);

console.log("WebSocket 服务启动完成,监听连接中...");

然后将以上代码保存为文件 server.js,使用下面命令:

node server.js

启动即可,如何测试下篇再说。。。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM