Last active
July 23, 2018 15:56
-
-
Save adamgotterer/2330b2dd05be28279b9dda0889ec8e91 to your computer and use it in GitHub Desktop.
Crystal WebSocket Client/Server Ping/Pong
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Client | |
require "http" | |
client = HTTP::WebSocket.new(URI.parse("ws://127.0.0.1:9333")) | |
client.send "ping" | |
client.on_message do |str| | |
puts str | |
client.send "ping" | |
sleep 1 | |
end | |
client.on_close do |str| | |
puts "disconnected" | |
end | |
client.run | |
# Server | |
require "http/server" | |
handler = HTTP::WebSocketHandler.new do |session| | |
puts session | |
session.on_message do |str| | |
puts str | |
session.send("pong") | |
sleep 1 | |
end | |
session.on_close do |str| | |
puts "closed" | |
puts str | |
end | |
end | |
server = HTTP::Server.new(handler) | |
puts "Listening on http://0.0.0.0:9333" | |
server.listen("0.0.0.0", 9333) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment