koa使用ws,scoket.io建立websocket连接,断开重连

2024-05-26 01:12

本文主要是介绍koa使用ws,scoket.io建立websocket连接,断开重连,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.使用ws建立socket连接,ws兼容性比socket.io要好一些

koa.js 

const Koa = require('koa'); // 引入 Koa 框架
const http = require('http'); // 引入 Node.js 的 http 模块
const { WebSocketServer } = require('ws'); // 引入 ws 模块中的 WebSocketServer
const cors = require('@koa/cors');const app = new Koa(); // 创建一个 Koa 应用实例
app.use(cors());// 创建一个 HTTP 服务器实例,并将 Koa 应用作为回调传递
const server = http.createServer(app.callback());// 创建一个 WebSocket 服务器实例,并将 HTTP 服务器作为参数传递
const wss = new WebSocketServer({ server });// 当有新的 WebSocket 连接时触发
wss.on('connection', function connection(ws) {// 处理 WebSocket 错误事件ws.on('error', console.error);// 处理收到消息事件ws.on('message', function message(data) {console.log('received: %s', data); // 打印收到的消息});// 发送初始消息给客户端ws.send('something');
});// 启动 HTTP 服务器并监听端口 8080
server.listen(8080, () => {console.log('Server is running at http://127.0.0.1:8080');
});

index.html 

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><div id="app"><button id="btn">send</button></div>
</body>
<script>function createConnection() {// 创建一个 WebSocket 实例,连接到服务器const socket = new WebSocket('ws://127.0.0.1:8080');// 处理收到的消息事件socket.onmessage = function (event) {console.log('Received message from server:', event.data);};// 处理连接关闭事件socket.onclose = function (event) {console.log('WebSocket is closed now.');setTimeout(() => {scoket = createConnection();}, 2000);};// 处理错误事件socket.onerror = function (error) {console.error('WebSocket error observed:', error);socket.close();};// 处理连接打开事件socket.onopen = function (event) {console.log('WebSocket is open now.');};return socket;}let socket = createConnection();// 获取按钮并添加点击事件处理程序document.getElementById('btn').addEventListener('click', function () {if (socket.readyState !== WebSocket.OPEN) {socket = createConnection();}socket.send('Hello, Server!');console.log('Message sent to server: Hello, Server!');});
</script></html>

2、socket.io

app.js

const koa = require('koa');
const http = require('http');
const SocketIO = require('socket.io');
const cors = require('@koa/cors');
const Router = require('@koa/router');
const fs = require('fs');
const router = new Router();const app = new koa();
app.use(cors());router.get('/index', (ctx) => {ctx.body = fs.readFileSync('./index2.html', 'utf-8');
});
app.use(router.routes());const server = http.createServer(app.callback());
const io = SocketIO(server);io.on('connect', client => {client.on('event', data => {console.log(data);});client.on('disconnect', () => {console.log('disconnect');});
});server.listen(8080, () => {console.log('127.0.0.1:8080');
});

index.html

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><div id="app"><button id="send">send</button></div>
</body>
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js" integrity="sha384-2huaZvOR9iDzHqslqwpR87isEmrfxqyWOF7hr7BY6KG0+hVKLoEXMPUJw3ynWuhO" crossorigin="anonymous"></script>
<script >// console.log('connect=',io.connect);let socket = io.connect('ws://127.0.0.1:8080');socket.on('connect', () => {console.log('connect');});socket.on('disconnect', () => {console.log('disconnect');});socket.on('event', (data) => {cosole.log(data);});document.getElementById('send').addEventListener('click',()=>{console.log(socket.connected,)socket.emit('event','hello !!!!!!!!');});
</script></html>

这篇关于koa使用ws,scoket.io建立websocket连接,断开重连的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1003143

相关文章

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据

在ASP.NET项目中如何使用C#生成二维码

《在ASP.NET项目中如何使用C#生成二维码》二维码(QRCode)已广泛应用于网址分享,支付链接等场景,本文将以ASP.NET为示例,演示如何实现输入文本/URL,生成二维码,在线显示与下载的完整... 目录创建前端页面(Index.cshtml)后端二维码生成逻辑(Index.cshtml.cs)总结

Spring Integration Redis 使用示例详解

《SpringIntegrationRedis使用示例详解》本文给大家介绍SpringIntegrationRedis的配置与使用,涵盖依赖添加、Redis连接设置、分布式锁实现、消息通道配置及... 目录一、依赖配置1.1 Maven 依赖1.2 Gradle 依赖二、Redis 连接配置2.1 配置 R

Python WSGI HTTP服务器Gunicorn使用详解

《PythonWSGIHTTP服务器Gunicorn使用详解》Gunicorn是Python的WSGI服务器,用于部署Flask/Django应用,性能高且稳定,支持多Worker类型与配置,可处... 目录一、什么是 Gunicorn?二、为什么需要Gunicorn?三、安装Gunicorn四、基本使用启

MySQL 临时表创建与使用详细说明

《MySQL临时表创建与使用详细说明》MySQL临时表是存储在内存或磁盘的临时数据表,会话结束时自动销毁,适合存储中间计算结果或临时数据集,其名称以#开头(如#TempTable),本文给大家介绍M... 目录mysql 临时表详细说明1.定义2.核心特性3.创建与使用4.典型应用场景5.生命周期管理6.注

python urllib模块使用操作方法

《pythonurllib模块使用操作方法》Python提供了多个库用于处理URL,常用的有urllib、requests和urlparse(Python3中为urllib.parse),下面是这些... 目录URL 处理库urllib 模块requests 库urlparse 和 urljoin编码和解码

使用Python提取PDF大纲(书签)的完整指南

《使用Python提取PDF大纲(书签)的完整指南》PDF大纲(Outline)​​是PDF文档中的导航结构,通常显示在阅读器的侧边栏中,方便用户快速跳转到文档的不同部分,大纲通常以层级结构组织,包含... 目录一、PDF大纲简介二、准备工作所需工具常见安装问题三、代码实现完整代码核心功能解析四、使用效果控

C#异步编程ConfigureAwait的使用小结

《C#异步编程ConfigureAwait的使用小结》本文介绍了异步编程在GUI和服务器端应用的优势,详细的介绍了async和await的关键作用,通过实例解析了在UI线程正确使用await.Conf... 异步编程是并发的一种形式,它有两大好处:对于面向终端用户的GUI程序,提高了响应能力对于服务器端应

MySQL慢查询工具的使用小结

《MySQL慢查询工具的使用小结》使用MySQL的慢查询工具可以帮助开发者识别和优化性能不佳的SQL查询,本文就来介绍一下MySQL的慢查询工具,具有一定的参考价值,感兴趣的可以了解一下... 目录一、启用慢查询日志1.1 编辑mysql配置文件1.2 重启MySQL服务二、配置动态参数(可选)三、分析慢查

MYSQL中information_schema的使用

《MYSQL中information_schema的使用》information_schema是MySQL中的一个虚拟数据库,用于提供关于MySQL服务器及其数据库的元数,这些元数据包括数据库名称、表... 目录关键要点什么是information_schema?主要功能使用示例mysql 中informa