-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient3.rb
More file actions
80 lines (66 loc) · 2.17 KB
/
Copy pathclient3.rb
File metadata and controls
80 lines (66 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Copyright notice:
# (C) 2009-2010
# This software is provided 'as-is' without any express or implied warranty.
# In no event will the authors be held liable for damages arising from the
# use of this software. All license is reserved.
# Object that mediates access between the server and the local chat window.
# This object establishes connections, receives messages, and sends messages.
# Last revision: December 3, 2009
require 'comm3.rb'
class ChatConnection
# Takes a callback block which accepts (type, sender, room, msg)
def initialize(&callback)
@comm = CryptoComm.new # Our connection to the server
@mutex = @comm.mutex
@msg_callback = callback
@room_names = { "\x00" * 8 => 'chat' }
@room_ids = { 'chat' => "\x00" * 8 }
@connected = false
end
attr_reader :room_names, :room_ids, :comm
def connected?
@connected
end
# Provide our mutex object to our owner
def mutex
@mutex
end
def mutex=(mtx)
@mutex = mtx
@comm.mutex = mtx
end
# method: connect to this addr on this port
def connect(addr, port, pub_key, name)
disconnect if @comm.connected?
@comm.open_ssl_socket(addr, port.to_i)
@comm.start_thread { |t, s, r, m| read_message(t, s, r, m) }
@comm.server_message([ "name", pub_key, name ].join(' '))
@connected = true
end
# Shut down the connection
def disconnect
@comm.shutdown
@connected = false
################## send notice of disconnection?
end
# We've received a message from the network
def read_message(type, sender_id, room_id, msg)
sender_name = @comm.sender_name(sender_id) || 'unknown_user'
room_name = @room_names[room_id]
type = type[0] if type.class == String
@msg_callback.call(type, sender_name, room_name, msg)
end
# We've received a chat message from the local user
def chat_msg(msg, room = 'chat')
room = @room_ids[room]
@mutex.synchronize do
@comm.broadcast_message(msg, room)
end
end
# We're sending a command - either to everyone, or to a specific user
def send_command(cmd_line, recipient = nil)
@mutex.synchronize do
@comm.send_command(cmd_line, recipient)
end
end
end # of ChatConnection class