Class: JSONSocket::Server
Instance Method Summary
collapse
#encode_json, #parse_json
Constructor Details
#initialize(host: "127.0.0.1", port: 1234, delimeter: "#", unix_socket: nil) ⇒ Server
Returns a new instance of Server.
24
25
26
27
28
29
30
31
32
33
|
# File 'lib/json-socket.rb', line 24
def initialize(host: "127.0.0.1", port: 1234, delimeter: "#", unix_socket: nil)
@delimeter = delimeter
@stop = false
@server = if unix_socket
FileUtils.rm_f(unix_socket)
UNIXServer.new unix_socket
else
TCPServer.new host, port
end
end
|
Instance Method Details
#listen ⇒ Object
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# File 'lib/json-socket.rb', line 39
def listen
loop do
Thread.start(@server.accept) do |client|
begin
client.set_encoding 'UTF-8'
message_length = client.gets(@delimeter).to_i
on_message(parse_json(client.read(message_length)), client)
rescue Exception => e
STDERR.puts e.message
end
end
break if @stop
end
end
|
#on_message(message, client) ⇒ Object
55
56
57
58
59
60
61
62
63
64
65
66
67
|
# File 'lib/json-socket.rb', line 55
def on_message(message, client)
puts "Default on_message method - please override like this: \n" \
" \n" \
"class CustomJSONSocketServer < JSONSocket::Server \n" \
" \n" \
" def on_message(message, client)\n" \
" puts message \n" \
" self.send_end_message([1,2,3], client)\n" \
" end \n" \
" \n" \
"end \n"
client.close
end
|
#send_end_message(message, client) ⇒ Object
69
70
71
72
73
74
|
# File 'lib/json-socket.rb', line 69
def send_end_message(message, client)
client.set_encoding 'UTF-8'
strigified = encode_json(message)
client << "#{strigified.bytesize}#{@delimeter}#{strigified}"
client.close
end
|
#stop ⇒ Object
35
36
37
|
# File 'lib/json-socket.rb', line 35
def stop
@stop = true
end
|