用 WebSocket:写一段实现实时对战中的双向通信的代码
时间: 2024-12-19 21:28:04 浏览: 16
在实时对战游戏中,WebSocket 是一种理想的选择,因为它允许服务器和客户端之间建立全双工的长连接,适合于实时数据传输。下面是一个简单的 JavaScript 示例,展示了如何使用 WebSocket 实现双向通信:
首先,在服务器端(例如 Node.js 使用 Express + ws 模块):
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log(`Received message from client: ${message}`);
// 这里可以将消息广播给所有已连接的客户端
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// 当客户端断开连接时,记录并关闭连接
ws.on('close', () => {
console.log('Client disconnected');
});
});
server.listen(8080, () => {
console.log('Server is running on port 8080');
});
然后,在客户端(JavaScript 浏览器):
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', (event) => {
console.log('Connected to server');
});
socket.addEventListener('message', (event) => {
console.log(`Received message: ${event.data}`);
// 发送响应或游戏指令
socket.send('Your response here');
});
socket.addEventListener('close', (event) => {
console.log('Connection closed');
});
这个示例中,当客户端向服务器发送一条消息时,服务器会接收并转发给其他所有连接的客户端。同样地,服务器接收到的消息也会逐个传递给客户端。