websocket 有没有一种方法可以在CC Tweaked with lua中正确编码json?

vcirk6k6  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(114)

我正在为ComputerCraft运行WebSocket服务器:调整了mod。我让服务器从Minecraft内部的turtle接收到一个JSON对象,但服务器无法将其作为JSON处理,并认为它只是一个字符串。
下面是我的Turtle代码(lua):

os.loadAPI("json")
local ws = nil
local err = nil

local function connectToServer(IP)
    ws,err = http.websocket(IP)
    if err then
        print('Connection Failed!')
        sleep(5)
        print('Retrying Connection')
        connectToServer(IP)
    else
        print('')
        print('Connected to Server')
        print('')
    end
end

connectToServer('ws://localhost:81')

if ws then
    while true do
        local msg = ws.receive()
        local obj = json.decode(msg)
        if msg == nil then
            print('Disconnected (Server Shutdown)')
            sleep(5)
            print('Retrying Connection')
            connectToServer('ws://localhost:81')
        elseif obj["type"] == 'client' then
            if obj["client"] == 'request' then
                ws.send(json.encodePretty("{type:'client', client:'turtle'}"))
        end
        elseif obj["type"] == 'shutdown' then
            os.setComputerLabel()
            os.shutdown()
        elseif obj["type"] == 'name' then
            os.setComputerLabel('Turtle '..obj["name"])
        else
            local obj = obj["type"]
            local func = loadstring(obj["func"])
            local success,data = func()
            print(data)
            if data then
                ws.send(json.encodePretty("{type:'turtle_status', task:obj, status:success, data:data}"))
            else
                ws.send(json.encodePretty("{type:'turtle_status', task:obj, status:success, data:none}"))
            end
        end
    end
end

下面是我的服务器代码(JavaScript):

const WebS = require("ws")
const wss = new WebS.Server({port:81})
let pageClients = []
let turtleClients = []
let consoleClients = []
let turtleLen = turtleClients.length
let pageLen = pageClients.length
let consoleLen = consoleClients.length
console.log('Server Started!')

wss.on('connection', (ws) => {
    let clientAddress = ws._socket.remoteAddress+":"+ws._socket.remotePort
    console.log('Something connected to the server. (Address: '+clientAddress+')');
    ws.send(JSON.stringify({type:"client", client:"request"}));
    ws.on('message', (data) => {
        let obj = JSON.parse(data);
        console.log(obj);
        if (obj.type === 'client'){
            console.log('Object is a client request. (Client: '+obj.client+')')
            let client = JSON.parse(data).client;
            if (client === 'console'){
                consoleClients.push(ws)
                consoleLen = consoleClients.length
                console.log('Client was a console. consoleLen: '+consoleLen)
                wss.broadcast(consoleClients, {type:"message", message:"Console "+consoleLen-1+" is online!"})
            }
            if (client === 'page'){
                pageClients.push(ws)
                pageLen = pageClients.length
                console.log('Client was a page. pageLen: '+pageLen)
                wss.broadcast(consoleClients, {type:"message", message:"Page "+pageLen-1+" is online!"})
            }
            if (client === 'turtle'){
                turtleClients.push(ws)
                turtleLen = turtleClients.length
                console.log('Client was a turtle. turtleLen: '+turtleLen)
                ws.send(JSON.stringify({type:"name", name:turtleLen}))
                wss.broadcast(consoleClients, {type:"message", message:"Turtle "+turtleLen-1+" is online!"})
            }
        }else if (obj.type === 'turtle_status'){
            ws.broadcast(pageClients, {type:obj.type, task:obj.task, status:obj.status, data:obj.data})
        }
    });
    function broadcast(clients, data){
        if (clients.length === 0){
            console.log('No clients to broadcast to.')
            return
        }
        clients.forEach(function each(client){
            client.send(JSON.stringify(data))
        })
    }
});

下面是服务器从turtle输出的内容:

Server Started!
Something connected to the server. (Address: ::1:27900)
{type:'client', client:'turtle'}

当它应该输出:

Server Started!
Something connected to the server. (Address: ::1:27900)
{type:'client', client:'turtle'}
Object is a client request. (Client: page)
Client was a turtle. turtleLen: 1
daolsyd0

daolsyd01#

我解决了这个问题。问题是,我使用的是ws.send(json.encode("{type:'client', client:'turtle'}"))而不是ws.send(json.encode({type='client', client='turtle'}))

相关问题