-
Notifications
You must be signed in to change notification settings - Fork 19
/
connection.rb
54 lines (44 loc) · 1.3 KB
/
connection.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
require 'forwardable'
module Celluloid
module WebSocket
module Client
class Connection
include Celluloid::IO
extend Forwardable
def initialize(url, handler)
@url = url
uri = URI.parse(url)
port = uri.port || (uri.scheme == "ws" ? 80 : 443)
@socket = Celluloid::IO::TCPSocket.new(uri.host, port)
@client = ::WebSocket::Driver.client(self)
@handler = handler
async.run
end
attr_reader :url
def run
@client.on('open') do |event|
@handler.async.on_open if @handler.respond_to?(:on_open)
end
@client.on('message') do |event|
@handler.async.on_message(event.data) if @handler.respond_to?(:on_message)
end
@client.on('close') do |event|
@handler.async.on_close(event.code, event.reason) if @handler.respond_to?(:on_close)
end
@client.start
loop do
begin
@client.parse(@socket.readpartial(1024))
rescue EOFError
break
end
end
end
def_delegators :@client, :text, :binary, :ping, :close, :protocol
def write(buffer)
@socket.write buffer
end
end
end
end
end