Minecraft基岩版WebSocket服务器启动报错,求排查修复方案
Minecraft基岩版WebSocket服务器修复方案
错误根因
你使用的websocket第三方包不支持直接通过port参数独立启动服务,必须先创建标准HTTP服务实例,再将WebSocket服务挂载到该HTTP服务上。
修复步骤
- 引入Node.js原生
http模块,先创建基础HTTP服务 - 将WebSocket服务挂载到已启动的HTTP服务上
- 移除无效冗余代码
wss.off - 将
SIGINT中断信号监听逻辑移到全局作用域,避免每次客户端连接重复注册监听导致内存泄漏
修复后完整代码
// Minecraft Bedrock WebSocket Server const http = require('http'); const webSocket = require('websocket'); const readline = require('readline'); const crypto = require('crypto'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // 创建基础HTTP服务 const httpServer = http.createServer((req, res) => { res.writeHead(200); res.end('WebSocket Server Running'); }); httpServer.listen(8000, () => { console.log("Server is running on your_ip:8000"); }); // 挂载WebSocket服务到HTTP服务 const wss = new webSocket.server({ httpServer: httpServer }); wss.on('connection', socket => { console.log("A client is opening a connection"); const command = () => { return new Promise((resolve) => { rl.question(`Command: /`, (cmd) => { // 发送命令,使用随机requestId避免响应匹配异常 socket.send(JSON.stringify( { "body": { "origin": { "type": "player" }, "commandLine": `${cmd}`, "version": 1 }, "header": { "requestId": crypto.randomUUID(), "messagePurpose": "commandRequest", "version": 1, "messageType": "commandRequest" } } )); console.log("Command sent\n\n"); resolve(); }); }); } async function askCommands() { while (true) { await command(); } } // 运行异步命令输入逻辑 askCommands(); socket.on('message', function incoming(message) { console.log('\nreceived: %s', message); }); }); // 全局监听中断信号 process.on('SIGINT', function() { console.log("\nInterrupt Ctrl-C"); process.exit(); });
使用注意事项
- 服务启动后,在Minecraft基岩版对应存档开启作弊模式,输入命令
/connect ws://<运行服务的设备IP>:8000即可完成连接 - 如无法连接请检查设备防火墙是否开放8000端口,确保游戏设备和服务运行设备在同一局域网下
内容的提问来源于stack exchange,提问作者MisledWater079
相关产品推荐
相关产品推荐

