Class: Celluloid::WebSocket

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Celluloid
Defined in:
lib/celluloid/websocket.rb,
lib/celluloid/websocket/rack.rb,
lib/celluloid/websocket/version.rb

Defined Under Namespace

Classes: DriverEnvironment, MessageStream

Constant Summary collapse

VERSION =
"0.0.6"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#envObject

Returns the value of attribute env.



13
14
15
# File 'lib/celluloid/websocket.rb', line 13

def env
  @env
end

#socketObject

Returns the value of attribute socket.



13
14
15
# File 'lib/celluloid/websocket.rb', line 13

def socket
  @socket
end

Class Method Details

.rack(config = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/celluloid/websocket/rack.rb', line 10

def self.rack(config={})
	lambda do |env|
		# We need to create the pool in the first request
		# because we might've been forked before.
		@pool ||= pool(config)

		if env['HTTP_UPGRADE'].nil? || env['HTTP_UPGRADE'].downcase != 'websocket'
			return [400, {}, "No Upgrade header or Upgrade not for websocket."]
		end

		env['rack.hijack'].call
		socket = Celluloid::IO::RackSocket.new(env['rack.hijack_io'].to_io)
		
		@pool.async.initialize_websocket(env, socket)
		[200,{},""]
	end
end

Instance Method Details

#closeObject



57
58
59
60
# File 'lib/celluloid/websocket.rb', line 57

def close
	@driver.close unless @driver.nil?
	@socket.close unless @socket.nil? || @socket.closed?
end

#closed?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/celluloid/websocket.rb', line 40

def closed?
	@socket.closed?
end

#initialize_websocket(env, socket) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/celluloid/websocket.rb', line 15

def initialize_websocket(env, socket)
	@env = env
	@socket = socket

	driver_env = DriverEnvironment.new(env, socket) 

	@driver = ::WebSocket::Driver.rack(driver_env)

	@driver.on(:close) do
		@socket.close
	end

	@message_stream = MessageStream.new(socket, @driver)

	@driver.start

	on_open if respond_to? :on_open
rescue EOFError
	close
end

#readObject



36
37
38
# File 'lib/celluloid/websocket.rb', line 36

def read
	@message_stream.read
end

#shutdownObject



62
63
64
# File 'lib/celluloid/websocket.rb', line 62

def shutdown
	close
end

#write(msg) ⇒ Object Also known as: <<



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/celluloid/websocket.rb', line 44

def write(msg)
	if msg.is_a? String
		@driver.text(msg)
	elsif msg.is_a? Array
		@driver.binary(msg)
	else
		raise "Can only send byte array or string over driver."
	end
rescue IOError, Errno::ECONNRESET, Errno::EPIPE
	raise SocketError, "error writing to socket"
end