我的 Computer-Craft 网络套接字客户端无法识别 JavaScript 服务器的响应(代码中的注释有助于解释)

服务器代码是普通的 JavaScript,而客户端代码是用 CC:tweaked 和其 web-socket 系统制作的(https://tweaked.cc/module/http.html#ty:Websocket:receive)。以下是客户端代码、发生事件的顺序以及发生的事情。

const WebSocket = require("ws"); // 引入库
const fs = require('fs');

var JSONvariables;

fs.readFile('C:/Users/Max/OneDrive/Documents/Dev/ThreeJS/turtleData.json', 'utf8' , (err, f) => {
    if (err) {
        console.error(err);
        return;
    }
    const pfile = JSON.parse(f);
    console.log(pfile.hades_values);
})

const wss = new WebSocket.Server({ // 初始化服务器
    port: 3738,
    URL: "localhost"
});

// 监听事件
wss.on("connection", ws => {
    console.log("客户端已连接。");

    ws.on("message", msg => {
        console.log("发现消息:" + msg);

        if(msg.substring(0, 5) == "Hades"){
            ws.send("前进");
            console.log("已发送消息。");
        }
    });

    ws.on("close", () => {
        console.log("客户端已断开连接。");
    });
});

服务器: 当客户端连接时 打印 "客户端已连接。" 在接收到客户端的消息时 打印 "发现消息:" 和消息 如果消息的开头是 "Hades" 向客户端发送 "ls" 打印 "已发送消息。" 当客户端断开连接时 打印 "客户端已断开连接。"

客户端: 打印 "启动!" 尝试连接服务器 打印 "尝试连接。" 如果服务器未连接 打印 "错误:" 打印错误 打印一个新行 如果服务器已连接 向服务器发送 "Hades 请求" 打印 "已连接" 一直循环 打印 "正在测试响应。" 尝试获得响应 如果响应中有内容 打印 "已找到响应。" 跳出循环 关闭网络套接字

--Lua 代码
-- 使用 https://tweaked.cc/module/http.html#ty:Websocket:receive

print("启动!")

local ws,err = http.websocket("ws://localhost:3738")
print("尝试连接。")

if not ws then
    print("错误:")
    printError(err)
    print("")
end

if ws then
    ws.send("Hades 请求 {nf31o2jheqioefh9}")
    print("已连接")

    while true do
        local response = ws.receive(1)
        print(response)
        if not response == nil then
            splitstring = response.split(response, ' ')
            print("分割字符串:")
            print(splitstring)
            shell.run(splitsring[1], splitstring[2])
            break
        end
    end

    ws.close()
end

我首先启动 JavaScript 程序 然后我会启动 Lua 程序

点赞