class

HTTP::WebSocket

Inherits Reference / Object

NOTE: To use WebSocket, you must explicitly import it with require "http/web_socket"

Constructors

new(uri : URI | String, headers : HTTP::Headers = HTTP::Headers.new) : self

Opens a new websocket using the information provided by the URI. This will also handle the handshake and will raise an exception if the handshake did not complete successfully. This method will also raise an exception if the URI is missing the host and/or the path.

Please note that the scheme will only be used to identify if TLS should be used or not. Therefore, schemes apart from wss and https will be treated as the default which is ws.

require "http/web_socket"

HTTP::WebSocket.new(URI.parse("ws://websocket.example.com/chat"))        # Creates a new WebSocket to `websocket.example.com`
HTTP::WebSocket.new(URI.parse("wss://websocket.example.com/chat"))       # Creates a new WebSocket with TLS to `websocket.example.com`
HTTP::WebSocket.new(URI.parse("http://websocket.example.com:8080/chat")) # Creates a new WebSocket to `websocket.example.com` on port `8080`
HTTP::WebSocket.new(URI.parse("ws://websocket.example.com/chat"),        # Creates a new WebSocket to `websocket.example.com` with an Authorization header
  HTTP::Headers{"Authorization" => "Bearer authtoken"})
HTTP::WebSocket.new(
  URI.parse("ws://user:password@websocket.example.com/chat")) # Creates a new WebSocket to `websocket.example.com` with an HTTP basic auth Authorization header
Source
new(host : String, path : String, port : Int32 | Nil = nil, tls : HTTP::Client::TLSContext = nil, headers : HTTP::Headers = HTTP::Headers.new) : self

Opens a new websocket to the target host. This will also handle the handshake and will raise an exception if the handshake did not complete successfully.

require "http/web_socket"

HTTP::WebSocket.new("websocket.example.com", "/chat")            # Creates a new WebSocket to `websocket.example.com`
HTTP::WebSocket.new("websocket.example.com", "/chat", tls: true) # Creates a new WebSocket with TLS to `ẁebsocket.example.com`
Source

Instance methods

close(code : CloseCode | Int | Nil = nil, message = nil) : Nil

Sends a close frame, and closes the connection. The close frame may contain a body (message) that indicates the reason for closing.

Source
closed?
Source
on_binary

Called when a binary message is received.

Source
on_close

Called when the connection is closed by the other party.

Source
on_message

Called when a text message is received.

Source
on_ping

Called when a PING frame is received.

Source
on_pong

Called when a PONG frame is received.

An unsolicited PONG frame should not be responded to.

Source
ping(message = nil)

Sends a PING frame. Received pings will call #on_ping.

The receiving party must respond with a PONG.

Source
pong(message = nil) : Nil

Sends a PONG frame, which must be in response to a previously received PING frame from #on_ping.

Source
receive

Receives and returns a single WebSocket message as a String for text messages, Bytes for binary messages, or raises IO::Error if the WebSocket has been closed.

# Open websocket connection
ws = HTTP::WebSocket.new("websocket.example.com", "/chat")

loop do
  case msg = ws.receive
  in String # text
    ws.send "response"
    puts msg
  in Bytes # binary
    ws.send "response".to_slice
  end
end
Source
receive?

Receives and returns a single WebSocket message as a String for text messages, Bytes for binary messages, or nil if the WebSocket has been closed.

# Open websocket connection
ws = HTTP::WebSocket.new("websocket.example.com", "/chat")

loop do
  case msg = ws.receive?
  in String # text
    ws.send "response"
    puts msg
  in Bytes # binary
    ws.send "response".to_slice
  in Nil
    break
  end
end
Source
run

Continuously receives messages and calls previously set callbacks until the websocket is closed. Ping and pong messages are automatically handled.

# Open websocket connection
ws = HTTP::WebSocket.new("websocket.example.com", "/chat")

# Set callback
ws.on_message do |msg|
  ws.send "response"
end

# Start infinite loop
ws.run
Source
send(message) : Nil

Sends a message payload (message).

Source
stream(binary = true, frame_size = 1024, &)

Stream data as one message with automatically fragmentation handling with respect to given frame_size. When the io is closed, current data in the buffer is sent in a FIN frame. The io is closed when the block returns.

The method accepts a block with an io argument. The io object can call on IO#write method. The write method accepts Bytes (Slice(UInt8)) and sends the data in chunks of frame_size bytes. For further information, see the HTTP::WebSocket::Protocol::StreamIO class.

# Open websocket connection
ws = HTTP::WebSocket.new("websocket.example.com", "/chat")

# Open stream
ws.stream(false, frame_size: 4) do |io|
  io.write "foo".encode("UTF-8") # Nothing is sent, buffer not full
  io.write "bar".encode("UTF-8") # Will send a first frame with "foob"
end                              # io is closed, a FIN frame with "bar" is sent
Source

Nested types