Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Implementing closing handshake.

  • Loading branch information...
commit f916535b7c73637191d1de7d620fe0028b5a0c5b 1 parent 0897f05
@gimite authored
Showing with 24 additions and 5 deletions.
  1. +22 −5 lib/web_socket.rb
  2. +2 −0  samples/stdio_client.rb
View
27 lib/web_socket.rb
@@ -104,6 +104,7 @@ def initialize(arg, params = {})
end
@received = []
@buffer = ""
+ @closing_started = false
end
attr_reader(:server, :header, :path)
@@ -146,10 +147,18 @@ def receive()
end
packet = gets("\xff")
return nil if !packet
- if !(packet =~ /\A\x00(.*)\xff\z/nm)
- raise(WebSocket::Error, "input must start with \\x00 and end with \\xff")
+ if packet =~ /\A\x00(.*)\xff\z/nm
+ return force_encoding($1, "UTF-8")
+ elsif packet == "\xff" && read(1) == "\x00" # closing
+ if @server
+ @socket.close()
+ else
+ close()
+ end
+ return nil
+ else
+ raise(WebSocket::Error, "input must be either '\\x00...\\xff' or '\\xff\\x00'")
end
- return force_encoding($1, "UTF-8")
end
def tcp_socket
@@ -167,8 +176,16 @@ def origin
def location
return "ws://#{self.host}#{@path}"
end
-
+
+ # Does closing handshake.
def close()
+ return if @closing_started
+ write("\xff\x00")
+ @socket.close() if !@server
+ @closing_started = true
+ end
+
+ def close_socket()
@socket.close()
end
@@ -304,7 +321,7 @@ def run(&block)
print_backtrace(ex)
ensure
begin
- ws.close() if ws
+ ws.close_socket() if ws
rescue
end
end
View
2  samples/stdio_client.rb
@@ -15,9 +15,11 @@
while data = client.receive()
printf("Received: %p\n", data)
end
+ exit()
end
$stdin.each_line() do |line|
data = line.chomp()
client.send(data)
printf("Sent: %p\n", data)
end
+client.close()
Please sign in to comment.
Something went wrong with that request. Please try again.