Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation for HTTP::WebSocket #9761

Merged
merged 3 commits into from
Sep 29, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/http/web_socket.cr
Original file line number Diff line number Diff line change
Expand Up @@ -48,25 +48,31 @@ class HTTP::WebSocket
new(Protocol.new(host, path, port, tls, headers))
end

# Called when the server sends a ping to a client.
def on_ping(&@on_ping : String ->)
end

# Called when the server receives a pong from a client.
def on_pong(&@on_pong : String ->)
end

# Called when the server recieves a text message from a client.
ibraheemdev marked this conversation as resolved.
Show resolved Hide resolved
def on_message(&@on_message : String ->)
end

# Called when the server recieves a binary message from a client.
ibraheemdev marked this conversation as resolved.
Show resolved Hide resolved
def on_binary(&@on_binary : Bytes ->)
end

# Called when the server closes a client's connection.
def on_close(&@on_close : CloseCode, String ->)
end

protected def check_open
raise IO::Error.new "Closed socket" if closed?
end

# Sends a message payload (message) to the client.
def send(message)
check_open
@ws.send(message)
Expand Down Expand Up @@ -102,12 +108,29 @@ class HTTP::WebSocket
close(nil, message)
end

# Sends a close frame to the client, and closes the connection.
# The close frame may contain a body (message) that indicates the reason for closing.
def close(code : CloseCode | Int? = nil, message = nil)
return if closed?
@closed = true
@ws.close(code, message)
end

# Continuously receives messages and calls previously set callbacks until the websocket is closed.
# Ping and pong messages are automatically handled.
#
# ```
# # Open websocket connection
# ws = WebSocket.new(uri)
#
# # Set callback
# ws.on_message do |msg|
# ws.send "response"
# end
#
# # Start infinite loop
# ws.run
# ```
def run
loop do
begin
Expand Down