Socket
2025年4月9日...大约 1 分钟前端开发Node.jsSocket
Socket.io用于实现基于事件的实时双向通信,分为服务端和客户端。
服务端
安装
// with npm
npm install socket.io
// with yarn
yarn add socket.io
启动服务
const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
// 静态文件服务
app.use(express.static(__dirname + "/public"));
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}/`);
});
事件
%% 建立连接 %%
io.on("connection", (socket) => {
%% 接收事件 %%
socket.on("事件名", () => {
%% 发送事件 %%
io.emit("事件名", {
%% 传递参数 %%
});
});
%% 仅接收一次事件 %%
socket.once("事件名", () => { ... });
%% 包含参数接收与回调函数的接收事件 %%
socket.on("事件名", (val, callback) => {
num = val;
callback &&
callback({
success: "ok",
data: {
message: "消息",
code: 100
},
});
});
});
客户端
安装
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io(); // 创建IO实例
</script>
使用
<script>
var num1 = 0;
var num2 = 0;
%% 监听事件 %%
socket.on("事件名", ({ val1, val2 }) => {
num1 = val1;
num2 = val2;
});
%% 发送事件 %%
socket.emit("事件名", val, (res) => {
...
})
</script>
总结
Socket.io的使用并不难,需要快速无误地写出合格的项目,需要提前对其进行梳理,通过整理并绘画泳道图等方式,可以使得后期的代码编写工作事半功倍。