Client
socketio.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Socket.io Demo</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.js"></script> <script> const socket = io('http://127.0.0.1:3000', { query: { token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjoxNDM0LCJvcGVyYXRvcl9pZCI6IjE0MzQ4NjMiLCJ1c2VybmFtZSI6ImxiX2FkbWluIiwibmlja25hbWUiOiIiLCJnYW1ldHlwZSI6ImxpdmUiLCJ0eXBlIjoxLCJtdXRlIjpmYWxzZX0sImlhdCI6MTY5MzMwMjczNywiZXhwIjoxNjkzMzA5OTM3fQ.9mj9jTj5XV37Wd5PSN8U_3fAgtHSy7ZYZMoUhlIvut0", }, transports: ['websocket'] }); socket.on('connect', () => { console.log('已连接到伺服器'); }); socket.on('chat', (msg) => { console.log(msg) document.getElementById('output').innerHTML += '<br>' + msg; }); function sendMessage() { const message = document.getElementById('inputMessage').value; socket.emit('send_message', message); } </script></head><body><h2>Socket.io</h2><input type="text" id="inputMessage" placeholder="输入消息"><button onclick="sendMessage()">发送消息</button><div id="output"></div></body></html>
Server
开一个资料夹取名叫 Server[命名随意]
将 server.js 放置其中
server.js
const express = require('express');const http = require('http');const { Server } = require('socket.io');const app = express();const server = http.createServer(app);const io = new Server(server);// 当有新的客户端连接时io.on('connection', (socket) => { console.log('一位用户已连接'); const jsonArray = [ { "username": "johnDoe", "accept-type": "credit-card", "amount": 100.50, "remark": "Payment for invoice #1234", "trans_room_id": "113001" }, { "username": "janeSmith", "accept-type": "paypal", "amount": 250.00, "remark": "Refund for order #5678", "trans_room_id": "113001" }, { "username": "aliceWong", "accept-type": "bank-transfer", "amount": 500.75, "remark": "Monthly subscription", "trans_room_id": "113001" } ]; //nsp.to(`otc_lobbylist`).emit('lobbylist', `{"command":"6601","data":` + JSON.stringify(JSON.stringify(jsonArray)) + `}`); io.emit('chat', `{"command":"6601","data":` + JSON.stringify(JSON.stringify(jsonArray)) + `}` ); // 接收 'send_message' 事件并发送给所有用户 socket.on('send_message', (message) => { io.emit('chat', message); }); socket.on('disconnect', () => { console.log('一位用户已断线'); });});// 伺服器启动const PORT = 3000;server.listen(PORT, () => { console.log(`伺服器正在运行于 http://localhost:${PORT}`);});
执行命令
npm init -ynpm install express socket.io