CC: Tweaked

CC: Tweaked

57M Downloads

wrong websocket documentation

Commandcracker opened this issue ยท 0 comments

commented

The documentation for websocketAsync is wrong.

Screenshot_20221207_161527

It returns true or false, error_message: str

@LuaFunction
public final Object[] websocket(String address, Optional<Map<?, ?>> headerTbl) throws LuaException {
if (!CoreConfig.httpWebsocketEnabled) {
throw new LuaException("Websocket connections are disabled");
}
var headers = getHeaders(headerTbl.orElse(Collections.emptyMap()));
try {
var uri = Websocket.checkUri(address);
if (!new Websocket(websockets, apiEnvironment, uri, address, headers).queue(Websocket::connect)) {
throw new LuaException("Too many websockets already open");
}
return new Object[]{ true };
} catch (HTTPRequestException e) {
return new Object[]{ false, e.getMessage() };
}
}

http.websocket also seams a bit wrong:

function websocket(_url, _headers)
expect(1, _url, "string")
expect(2, _headers, "table", "nil")
local ok, err = nativeWebsocket(_url, _headers)
if not ok then return ok, err end
while true do
local event, url, param = os.pullEvent( )
if event == "websocket_success" and url == _url then
return param
elseif event == "websocket_failure" and url == _url then
return false, param
end
end
end

I also found out, when a web-socket server is not responding (creating a ws connection)
then http.websocket will wait about 1min and then cancel the connection.

some way of setting a timeout would be nice like in Websocket.receive

my current workaround / implementation is this:

function websocket_with_timeout(_url, _headers, _timeout)
    if http.websocketAsync then
        local websocket, websocket_error = http.websocketAsync(_url, _headers)
        if not websocket then
            return false, websocket_error
        end

        local timerID = os.startTimer(_timeout)

        while true do
            local event, param1, param2 = os.pullEvent()

            -- TODO: Close web-socket when the connection succeeds after the timeout
            if event == "websocket_success" and param1 == _url then
                return param2
            elseif event == "websocket_failure" and param1 == _url then
                return false, param2
            elseif event == "timer" and param1 == timerID then
                return false, "Timeout"
            end
        end
    end

    -- use websocket without timeout
    -- when the CC version dos not support websocketAsync
    return http.websocket(_url, _headers)
end