http.websocket

Attempt to establish a WebSocket connection to the given URL.

ExampleCreating a websocket (blocking send/receive)
Connects to ws://demos.kaazing.com/echo (a server that responds with the exact data sent to it).
Code
<nowiki>
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()
    </nowiki>
Output Prints Hello world!
ExampleCreating 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
<nowiki>
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
    </nowiki>
Output Prints Hello world!

http.websocket
Function
Syntax
http.websocket(
  • url : string
  • headers? : table
)

Returns table handle | nil, string err
API http
Source CC:Tweaked (source) (source)
This article is issued from Computercraft. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.