Permalink
Browse files

First part of server

  • Loading branch information...
imanel committed Jul 13, 2012
1 parent df39dbc commit 29a3ae44c13266e669c136b56566493ff463c2dd
Showing with 91 additions and 1 deletion.
  1. +1 −1 examples/base.rb
  2. +60 −0 lib/websocket/handshake/base.rb
  3. +30 −0 lib/websocket/handshake/server.rb
View
@@ -101,7 +101,7 @@ def handle_connecting(data)
@handshake << data
return unless @handshake.finished?
if @handshake.valid?
- send(@handshake.response.to_s, :type => :plain) unless @handshake.response.nil?
+ send(@handshake.to_s, :type => :plain) unless @handshake.should_respond?
@frame = WebSocket::Frame::Incoming.new(:version => @handshake.version)
@state = :open
trigger_onopen
@@ -2,6 +2,66 @@ module WebSocket
module Handshake
class Base
+ attr_reader :host, :port, :path, :query,
+ :error, :state, :version
+
+ def initialize(args = {})
+ @state = :new
+
+ @data = ""
+ @headers = {}
+ end
+
+ def <<(data)
+ raise NotImplementedError
+ end
+
+ def finished?
+ @state == :finished
+ end
+
+ def valid?
+ finished? && @error == nil
+ end
+
+ def should_respond?
+ raise NotImplementedError
+ end
+
+ private
+
+ def set_error(message)
+ @state = :error
+ @error = message
+ end
+
+ def include_version
+ case @version
+ when 13 then include Handler::Handler13
+ else set_error('Unknown version') and return false
+ end
+ return true
+ end
+
+ HEADER = /^([^:]+):\s*(.+)$/
+
+ def parse_data
+ header, @leftovers = data.split("\r\n\r\n", 2)
+ return unless @leftovers # The whole header has not been received yet.
+
+ lines = header.split("\r\n")
+
+ first_line = lines.shift
+ return unless parse_first_line(first_line)
+
+ lines.each do |line|
+ h = HEADER.match(line)
+ @headers[h[1].strip.downcase] = h[2].strip if h
+ end
+
+ @state = :finished
+ end
+
end
end
end
@@ -2,6 +2,36 @@ module WebSocket
module Handshake
class Server < Base
+ def <<(data)
+ @data << data
+ parse_data
+ set_version
+ end
+
+ def should_respond?
+ true
+ end
+
+ private
+
+ # TODO: Add support for #75 & #76
+ def set_version
+ @version = @headers['Sec-WebSocket-Version'].to_i
+ include_version
+ end
+
+ PATH = /^(\w+) (\/[^\s]*) HTTP\/1\.1$/
+
+ def parse_first_line(line)
+ method = line[1].strip
+ set_error("Must be GET request") and return unless method == "GET"
+
+ resource_name = line[2].strip
+ path, query = resource_name.split('?', 2)
+
+ return true
+ end
+
end
end
end

0 comments on commit 29a3ae4

Please sign in to comment.