Node极速开发WebSocket服务器

  1. 首先讲出核心代码index.js,如下:
const crypto = require('crypto'); const express = require('express'); const { createServer } = require('http'); const WebSocket = require('ws'); const app = express(); const server = createServer(app); const wss = new WebSocket.Server({ server }); wss.on('connection', function(ws) { console.log("client joined."); // send "hello world" interval const textInterval = setInterval(() => ws.send("hello world!"), 100); // send random bytes interval const binaryInterval = setInterval(() => ws.send(crypto.randomBytes(8).buffer), 110); ws.on('message', function(data) { if (typeof(data) === "string") { // client sent a string console.log("string received from client -> '" + data + "'"); } else { console.log("binary received from client -> " + Array.from(data).join(", ") + ""); } }); ws.on('close', function() { console.log("client left."); clearInterval(textInterval); clearInterval(binaryInterval); }); }); server.listen(8080, function() { console.log('Listening on http://localhost:8080'); });

  1. 其次,讲明使用的库,写入packages.json文件中,如下:
{ "name": "nodeserver", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1", "ws": "^7.1.2" } }

  1. 最后,执行即可,先npm install安装依赖包,再执行npm run start或直接执行node index.js

  1. 基于Node.js的WebSocket极简服务器开发完成。




作者:艾孜尔江


__EOF__

本文作者艾孜尔江
本文链接https://www.cnblogs.com/ezhar/p/14329222.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   艾孜尔江  阅读(112)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示