官网地址:Socket.IO
项目结构:
服务端(node)代码:
首先安装 express,socket.io
npm i express socket.io -S
/server/index.js
// 官网用例:https://socket.io/zh-CN/docs/v4/server-initialization/#with-express
const express = require('express');
const { createServer } = require("http");
const { Server } = require("socket.io");
const app = express();
//设置静态资源地址
app.use(express.static('../web'));
//开启一个websocket服务
const httpServer = createServer(app);
const io = new Server(httpServer);
//推送消息的代码,必须写到触发connection的回调函数中
//其中的socket代表的是当前客户端
io.on('connection', function (socket) {
console.log('a user connected');
//服务器主动向客户端推送消息,有字符串msg标识的嵌套字发出事件处理程序
//emit表示给客户端推送信息,
socket.emit('msg', { id: 1, username: '客户端第一次接受数据' });
// hello是和客户端约定的事件名称
socket.on('hello', (data) => {
console.log(data);
socket.emit('msg', '服务器:' + data.split('').reverse().join(''));
})
});
httpServer.listen(3000, () => {
console.log('this server is running at http://localhost:3000');
});
前端代码:
/web/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>前后端通信</title>
</head>
<body>
<input type="text" id="inp">
<button onclick="send()">发送消息</button>
<button onclick="disconnect()">断开连接</button>
<button onclick="connect()">重新连接</button>
</body>
<!-- 在客户端的首先第一步,必须先引入socket.io这个库 -->
<!-- <script src="./socket.io.js"></script> -->
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js"></script>
<script>
const inp = document.getElementById('inp');
//建立一个有效的url、地址
const url = 'ws://localhost:3000';
//客户端请求连接到websocket服务器
const socket = io(url);
//监听是否连接成功
socket.on('connect', () => {
console.log('连接成功....');
});
//监听服务器传送过来的msg事件处理程序
socket.on('msg', function(data) {
//拿到数据
console.log(data);
});
// 监听断开连接
socket.on("disconnect", (reason) => {
console.log(reason + ' 连接已断开...');
});
function send() {
// socket.emit 在断开连接时会缓存发送的数据,连接后会一并发出
// socket.volatile.emit 在断开后不缓存发送的数据
// 官网地址:https://socket.io/zh-CN/docs/v4/client-offline-behavior/
socket.volatile.emit('hello', inp.value);
}
function disconnect() {
socket.disconnect();
}
function connect() {
socket.connect();
}
</script>
</html>