-
Notifications
You must be signed in to change notification settings - Fork 3
/
Server.py
52 lines (40 loc) · 1.75 KB
/
Server.py
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
import SocketServer, time, json
MESSAGE_BUFFER = []
class MyTCPHandler(SocketServer.StreamRequestHandler):
def handle(self):
bufLength = 0
while True:
self.data = self.rfile.readline().strip()
if self.data == '':
time.sleep(0.5)
continue
print "{} wrote: {}".format(self.client_address[0], self.data)
try:
jData = json.loads(self.data)
except ValueError as er:
print 'Malformed Packet:', self.data
continue
if jData['type'] == 'login':
#print 'login type'
self.writeMessage(jData['user'], '<-- %s has Logged In -->' % jData['user'])
if not len(MESSAGE_BUFFER) == bufLength:
bufDiff = len(MESSAGE_BUFFER) - bufLength
bufLength = len(MESSAGE_BUFFER)
for msg in MESSAGE_BUFFER[-bufDiff:]:
data = json.dumps(msg)
data = data + '\n'
print 'written to output: %s' %data
self.wfile.write(data)
time.sleep(0.5)
def writeMessage(self, user, message):
MESSAGE_BUFFER.append({'user':user, 'message':message})
if __name__ == "__main__":
HOST, PORT = "localhost", 9984
# Create the server, binding to localhost on port 9999
server = SocketServer.ThreadingTCPServer((HOST, PORT),
RequestHandlerClass=MyTCPHandler,
bind_and_activate=False)
server.allow_reuse_address = True
server.server_bind()
server.server_activate()
server.serve_forever()