Permalink
Browse files

Refactored single class into client, server, frame, and util. Added W…

…ebSocket namespace and somewhat invalidated the name of the library and gem.
  • Loading branch information...
1 parent 8c053b7 commit 235f863faf48983da41f8181a18b936875c3539b Dan committed Dec 30, 2009
View
@@ -33,7 +33,7 @@ Not yet... coming soon
#create a channel for pub sub
$chatroom = EM::Channel.new
- class ChatServer < WebSocketServer
+ class ChatServer < WebSocket::Server
#subscribe to the channel on client connect
def on_connect
View
@@ -11,7 +11,7 @@ <h1>em-websocket-server chat demo</h1>
<script>
- var webSocket = new WebSocket('ws://192.168.0.2:8000/time');
+ var webSocket = new WebSocket('ws://localhost:8000/time');
webSocket.onopen = function(event){
document.getElementById('chat').innerHTML = 'connected';
View
@@ -1,30 +1,70 @@
$:.unshift File.dirname(__FILE__) + '/../lib'
require 'rubygems'
-require 'em-websocket-server'
+require 'web_socket'
require 'json'
$chatroom = EM::Channel.new
+$messages = 0
-class ChatServer < WebSocketServer
+class ChatServer < WebSocket::Server
def on_connect
+ puts "Server -> Connect"
@sid = $chatroom.subscribe do |msg|
send_message msg
end
end
def on_disconnect
+ puts "Server -> Handle Disconnect"
$chatroom.unsubscribe(@sid)
end
def on_receive msg
- $chatroom.push msg
+
+ $messages += 1
+ if($messages % 100 == 0)
+ puts $messages
+ end
+
+ $chatroom.push(msg)
+ end
+
+end
+
+class ChatClient < WebSocket::Client
+
+ def initialize *args
+ super
+ end
+
+ def on_disconnect
+ puts "Client -> Disconnected"
+ end
+
+ def on_connect
+
+ EM.add_periodic_timer(rand() * 8, EM.Callback(self, :on_timer))
+
+ puts "Client -> connected"
+
+ end
+
+ def on_timer
+ send_message "x"
+ end
+
+ def on_receive msg
end
end
+EM.kqueue
EM.run do
EM.start_server "0.0.0.0", 8000, ChatServer
+ 5.times do
+ EM.connect "localhost", 8000, ChatClient
+ end
end
@@ -18,7 +18,7 @@ var TicTacToe = new Class({
initialize: function() {
if (TicTacToe.connection == null) {
- TicTacToe.connection = new WebSocket('ws://192.168.0.2:8000/tictactoe');
+ TicTacToe.connection = new WebSocket('ws://localhost:8000/tictactoe');
};
TicTacToe.connection.onopen = this.join.bind(this);
@@ -1,7 +1,7 @@
$:.unshift File.dirname(__FILE__) + '/../../lib'
require 'rubygems'
-require 'em-websocket-server'
+require 'web_socket'
require 'json'
require 'uuid'
require 'pp'
@@ -108,7 +108,7 @@ def toggle
end
end
-class TickTackToeServer < WebSocketServer
+class TickTackToeServer < WebSocket::Server
attr_accessor :game_id, :key, :status_key
View
@@ -9,7 +9,7 @@ <h1>em-websocket-server timesync demo</h1>
<h2 id="time">opening socket</h2>
<script>
- var webSocket = new WebSocket('ws://192.168.0.2:8000/time');
+ var webSocket = new WebSocket('ws://localhost:8000/time');
webSocket.onopen = function(event){
document.getElementById('time').innerHTML = 'waiting for socket';
View
@@ -1,33 +1,35 @@
$:.unshift File.dirname(__FILE__) + '/../lib'
require 'rubygems'
-require 'em-websocket-server'
+require 'web_socket'
require 'json'
-class TimeServer < WebSocketServer
+class TimeServer < WebSocket::Server
def on_connect
- @timer = EM.add_periodic_timer(5) do
- sync_time
- end
+ puts "Connection Accepted"
+ @timer = EM.add_periodic_timer(5, EM.Callback(self, :sync_time))
end
def on_disconnect
- @timer
+ puts "Connection released"
+ EM.cancel_timer @timer
end
def on_receive msg
- puts "msg rcv"
end
def sync_time
+ puts "Hi"
send_message({ :time => Time.now }.to_json)
end
end
-EM.epoll
+EM.epoll = true if EM.epoll?
+EM.kqueue = true if EM.kqueue?
+
EM.set_descriptor_table_size(10240)
EM.run do
View
@@ -1,158 +0,0 @@
-require 'rubygems'
-require 'eventmachine'
-
-class WebSocketServer < EM::Connection
-
- @@logger = nil
- @@num_connections = 0
- @@path_regex = /^GET (\/[^\s]*) HTTP\/1\.1$/
- @@header_regex = /^([^:]+):\s*([^$]+)/
- @@callbacks = {}
- @@accepted_origins = []
-
- attr_accessor :connected,
- :headers,
- :path
-
- def initialize *args
- super
- @connected = false
- end
-
- def valid_origin?
- @@accepted_origins.empty? || @@accepted_origins.include?(origin)
- end
-
- #not doing anything with this yet
- def valid_path?
- true
- end
-
- def valid_upgrade?
- @headers["Upgrade"] =~ /websocket/i
- end
-
- def origin
- @headers["Origin"]
- end
-
- def host
- @headers["Host"]
- end
-
- def self.path name, &block
- @@callbacks[name] = block
- end
-
- #tcp connection established
- def post_init
- @@num_connections += 1
- end
-
- #must be public for em
- def unbind
- @@num_connections -= 1
- on_disconnect
- end
-
- # Frames need to start with 0x00-0x7f byte and end with
- # an 0xFF byte. Per spec, we can also set the first
- # byte to a value betweent 0x80 and 0xFF, followed by
- # a leading length indicator. No support yet
- def send_message msg
- send_data "\x00#{msg}\xff"
- end
-
- protected
-
- #override this method
- def on_receive msg
- log msg
- end
-
- #override this method
- def on_connect
- log "connected"
- end
-
- #override this method
- def on_disconnect
- log "disconnected"
- end
-
- def log msg
- if @@logger
- @@logger.info msg
- else
- puts msg
- end
- end
-
- private
-
- # when the connection receives data from the client
- # we either handshake or handle the message at
- # the app layer
- def receive_data data
- unless @connected
- handshake data
- else
- on_receive data.gsub(/^(\x00)|(\xff)$/, "")
- end
- end
-
- # parse the headers, validate the origin and path
- # and respond with appropiate headers for a
- # healthy relationship with the client
- def handshake data
-
- #convert the headers to a hash
- parse_headers data
-
- # close the connection if the connection
- # originates from an invalid source
- close_connection unless valid_origin?
-
- # close the connection if a callback
- # is not registered for the path
- close_connection unless valid_path?
-
- # don't respond to non-websocket HTTP requests
- close_connection unless valid_upgrade?
-
- #complete the handshake
- send_headers
-
- @connected = true
-
- on_connect
- end
-
- # send the handshake response headers to
- # complete the initial com
- def send_headers
-
- response = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
- response << "Upgrade: WebSocket\r\n"
- response << "Connection: Upgrade\r\n"
- response << "WebSocket-Origin: #{origin}\r\n"
- response << "WebSocket-Location: ws://#{host}#{path}\r\n\r\n"
-
- send_data response
- end
-
- # turn http style headers into a ruby hash
- # TODO: this is probably not done "well"
- def parse_headers data
- lines = data.split("\r\n")
-
- @path = @@path_regex.match(lines.shift)[1]
- @headers = {}
-
- lines.each do |line|
- kvp = @@header_regex.match(line)
- @headers[kvp[1].strip] = kvp[2].strip
- end
- end
-
-end
View
@@ -0,0 +1,11 @@
+require 'rubygems'
+require 'eventmachine'
+require 'pp'
+
+module WebSocket
+end
+
+require 'web_socket/util.rb'
+require 'web_socket/frame.rb'
+require 'web_socket/server.rb'
+require 'web_socket/client.rb'
Oops, something went wrong.

0 comments on commit 235f863

Please sign in to comment.