http.websocket

From ComputerCraft
Jump to navigation Jump to search

http.websocket
Function
Syntax
http.websocket()
Returns table handle | nil, string err
API http
Source CC:Tweaked (source) (source)

Attempt to establish a WebSocket connection to the given URL.

ExampleExampleCreating a websocket (blocking send/receive)
Connects to ws://demos.kaazing.com/echo (a server that responds with the exact data sent to it).
Code
local ws, err = http.websocket("ws://demos.kaazing.com/echo")
if not ws then
  return printError(err)
end

ws.send("Hello world!")
local response = ws.receive()
assert(response == "Hello world!", "Received wrong response!")
print(response)

-- Don't forget to close the connection!
ws.close()
Output Prints Hello world!
ExampleExampleCreating a websocket (event based)
Connects to ws://demos.kaazing.com/echo, but uses events to receive messages rather than the receive method. This way of receiving events has the advantage that the program is able to respond to other events while waiting for a response, whereas the former method will block on ws.receive().
Code
local connectionURL = "ws://demos.kaazing.com/echo"
local ws, err = http.websocket(connectionURL)
if not ws then
  return printError(err)
end

ws.send("Hello world!")

while true do
  local _, url, response, isBinary = os.pullEvent("websocket_message")

  -- We need this if statement to check that we received the message from
  -- the correct websocket. After all, you can have many websockets connected to
  -- different URLs.
  if url == connectionURL then
    assert(response == "Hello world!", "Received wrong response!")
    print(response)

    -- Don't forget to close the connection!
    ws.close()

    -- We've received our response and are finished.
    break
  end  
end
Output Prints Hello world!