update README
[sunshowers.git] / examples / echo_client.rb
blob1702366d0d9b078de7592e8d100e889f9c3230df
1 #!/usr/bin/ruby
2 # this is designed to work with the echo_wsh.py handler for pywebsocket
3 # -*- encoding: binary -*-
4 require 'socket'
5 require 'sunshowers'
7 host_with_port = ARGV.shift or abort "Usage: #$0 HOST:PORT"
8 host, port = host_with_port.split(/:/)
9 port ||= 80
11 write_method = ARGV.shift || :write_utf8
12 write_method = write_method.to_sym
14 req =
15   "GET /echo HTTP/1.1\r\n" \
16   "Upgrade: WebSocket\r\n" \
17   "Connection: Upgrade\r\n" \
18   "Host: #{host_with_port}\r\n" \
19   "Origin: http://#{host_with_port}/\r\n" \
20   "\r\n"
22 # yes we cut corners here
23 sock = TCPSocket.new(host, port.to_i)
24 sock.syswrite(req)
25 buf = ""
26 begin
27   buf << sock.readpartial(16384)
28 end while buf !~ /\r\n\r\n/
29 p [ :handshake_header, buf ]
31 sock = Sunshowers::IO.new(sock)
32 sock.write_utf8 "HELLO"
33 p sock.gets
35 puts "enter whatever you want, Ctrl-D to exit write_method=#{write_method}"
36 begin
37   while line = STDIN.gets
38     sock.__send__ write_method, line
39     p sock.gets
40   end
41 rescue EOFError
42 ensure
43   sock.write_utf8 "Goodbye"
44   p sock.gets
45 end