nodejs websocket server

本文介绍如何使用Node.js和ws库创建WebSocket服务端。通过示例代码展示了如何监听连接、接收消息及发送响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装:

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

转载于:https://www.cnblogs.com/zhen-android/p/7634888.html

### 如何使用 Node.js 创建 WebSocket 服务器 创建 WebSocket 服务器的过程涉及安装必要的依赖项并编写相应的代码逻辑。以下是具体方法: #### 安装 ws 库 为了简化 WebSocket 的开发工作,可以利用 `ws` 这一流行的 WebSocket 实现库[^1]。通过 npm (Node Package Manager) 来安装此库: ```bash npm install ws ``` #### 编写 WebSocket 服务器代码 一旦安装完成,就可以着手构建 WebSocket 服务器实例了。下面是一份简单的示例代码片段用于启动监听于8080端口上的 WebSocket 服务器[^2]: ```javascript const WebSocket = require('ws'); // 创建一个WebSocket服务器,在8080端口启动 const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { console.log("New client connected"); ws.on('message', function incoming(message) { console.log(`Received message => ${message}`); // 广播接收到的消息给所有连接的客户端 wss.clients.forEach(function each(client) { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(message); } }); }); ws.on('close', function close() { console.log('Client has disconnected'); }); }); console.log('Server started on ws://localhost:8080/'); ``` 这段脚本不仅定义了一个基础的服务端框架,还包含了处理新连接、接收消息以及当某个会话关闭时执行相应操作的功能。 除了 `ws` 外,还有其他几种常用的 WebSocket 实现在 Node.js 中可供选择,比如 µWebSockets, Socket.IO 和 WebSocket-Node 等工具也提供了不同的特性和接口设计供开发者依据项目需求选用[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值