Last active
August 29, 2015 14:26
-
-
Save kylekyle/2aa7720b7293fa3e60d6 to your computer and use it in GitHub Desktop.
An example of creating a barebones web socket server and client in Ruby
This file contains hidden or 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
require 'socket' | |
require 'websocket' | |
require 'websocket-client-simple' | |
port = rand(10_000..60_000) | |
thread = Thread.new do | |
begin | |
server = TCPServer.new port | |
socket = server.accept | |
handshake = WebSocket::Handshake::Server.new | |
handshake << socket.gets until handshake.finished? | |
socket.write handshake.to_s | |
incoming = WebSocket::Frame::Incoming::Server.new version: handshake.version | |
incoming << socket.getc until message = incoming.next | |
puts message.data | |
ensure | |
server.close | |
end | |
end | |
begin | |
client = WebSocket::Client::Simple.connect "ws://localhost:#{port}" | |
client.on(:open) { client.send 'Ruby WebSockets!' } | |
thread.join | |
ensure | |
client.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment