-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.py
More file actions
87 lines (76 loc) · 2.82 KB
/
server.py
File metadata and controls
87 lines (76 loc) · 2.82 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
81
82
83
84
85
86
87
import socket
import threading
import datetime
import time
import json
class ServerThread(threading.Thread):
def __init__(self, cons_list, client, address, addr_list):
threading.Thread.__init__(self)
self.client = client
self.address = address
self.cons_list = cons_list
self.addr_list = addr_list
def run(self):
while True:
raw_data = self.client.recv(4096)
if not raw_data:
# client is off-line, remove it and break the thread
self.cons_list.remove(self.client)
self.addr_list.remove(self.address)
break
# extract info from raw data
data = json.loads(raw_data)
text = data['msg']
mode = data['private_mode']
if mode in ['', 'None']:
# public mode
for client in self.cons_list:
client.send(self.msg_build(text, False))
else:
# private mode
ip, port = str(mode).split(':')
for i in range(len(self.cons_list)):
if self.cmpT(self.addr_list[i], (ip, int(port))):
# send msg to the specified ip and port
self.cons_list[i].send(self.msg_build(text, True))
# display msg to sender
if self.cons_list[i] is not self.client:
self.client.send(self.msg_build(text, True))
break
# construct the message
def msg_build(self, text, private=False):
send_time = datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M')
msg = ''
if private:
msg += '(Private Mode)'
msg += 'From host: ' + self.address[0] + ', port: ' + str(
self.address[1]) + ', time: ' + send_time + " \n " + text
return json.dumps({'msg': msg, 'cons': [x for x in self.addr_list]})
# compare two list
def cmpT(self, t1, t2):
return sorted(t1) == sorted(t2)
class Server():
def __init__(self):
self.server = socket.socket()
self.host = '127.0.0.1'
self.port = 12345
self.server.bind((self.host, self.port))
self.server.listen(5)
self.cons_list = []
self.addr_list = []
self.thread = None
def run(self):
while True:
try:
con, addr = self.server.accept()
print 'New Connection:', addr
self.cons_list.append(con)
self.addr_list.append(addr)
self.thread = ServerThread(self.cons_list, con, addr, self.addr_list)
self.thread.start()
except Exception, e:
print e
break
self.server.close()
s = Server()
s.run()