本文主要是介绍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连接,断开重连的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!