Skip to content

Instantly share code, notes, and snippets.

@pochi
Created May 6, 2012 10:28
Show Gist options
  • Save pochi/2621510 to your computer and use it in GitHub Desktop.
Save pochi/2621510 to your computer and use it in GitHub Desktop.
# coding: utf-8
require "socket"
require 'libwebsocket'
require 'eventmachine'
class WebSocket
def initialize(url, params = {})
@hs ||= LibWebSocket::OpeningHandshake::Client.new(:url => url, :version => params[:version])
@frame ||= LibWebSocket::Frame.new
@socket = TCPSocket.new(@hs.url.host, @hs.url.port || 80)
@socket.write(@hs.to_s)
@socket.flush
loop do
data = @socket.getc
next if data.nil?
result = @hs.parse(data.chr)
raise @hs.error unless result
[25/143]
if @hs.done?
@handshaked = true
break
end
end
end
def send(data)
raise "no handshake!" unless @handshaked
data = @frame.new(data).to_s
@socket.write data
@socket.flush
end
def receive
raise "no handshake!" unless @handshaked
data = @socket.gets("\xff")
@frame.append(data)
messages = []
while message = @frame.next
messages << message
end
messages
end
def socket
@socket
end
def close
@socket.close
end
end
def ping_pong(num)
client = WebSocket.new("http://localhost:8080/")
loop do
client.send(num.to_s)
sleep(0.1*rand(1000))
end
end
threads = []
1000.times do |i|
threads << Thread.new(i) do |num|
ping_pong(num)
end
end
threads.each { |t| t.join }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment