CC: Tweaked

CC: Tweaked

57M Downloads

Websocket closing after receiving or sending a message

auroraveon opened this issue ยท 0 comments

commented

Minecraft Version

1.16.x

Version

1.99.1

Details

I'm currently working on a project that uses a python websocket server to communicate to turtles running their respective client code.

However, after the lua websocket client receives or sends a message, it closes the websocket and then throws the following error after it tries to receive or send (in this case receive - see client code below):

main.lua:14: attempt to use a closed file

The client function loop (only the loop is included as the other stuff is just variables):

function client()
    local ws, err = http.websocket(URL) -- the websocket
    if err then
        print('Error: '..err)
    elseif ws then
        print('Connected! Listening on port '..tostring(PORT))

        while true do
            local msg = ws.receive() -- <--- this is where the error occurs from

            if msg == nil then
                break
            elseif string.find(msg, "^Server:") then
                print(msg)
            else
                local func , err = load(msg) -- code from the server
                if not err then
                    print('Executing code: '..msg)
                    local result = func () -- the return data
                    ws.send(json:encode({data=result}))
                else
                    print('Error: '..'Remote code could not execute.')
                end
            end
        end
    end
end

Here is another websocket client implementation that is much simpler and still has the same error:

local ws, err = http.websocket("ws://127.0.0.1:7890")

if err then
    print(err)
elseif ws then
    print('Connected!')
    while true do
        local msg = ws.receive()
        print(msg)
    end
end

And this gives this output to the turtle's console:
image

Also please excuse any bad lua code practices because I'm quite new to it.

I'm happy to provide any other information required to find the issue.