-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.py
112 lines (78 loc) · 2.47 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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from tornado import websocket, web, ioloop, httpserver
import tornado
import ast #to convert unicode type to dict type
from Session import Session
import json
#list of WebSocket connections
connections={}
session = Session()
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print ("WebSocket opened")
print ("from %s" %self.request.remote_ip)
def on_message(self, message):
#if socket id not defined yet, set it to 0
if( hasattr(self,"id") == False ):
self.id = 0
#When a message comes in on a socket,the player id can be obtained from the socket
#and passed on to the handler
messageHandler.handleIncomingMsg(message,self,self.id)
def on_close(self):
print ("WebSocket closed")
class MessageHandler:
def __init__(self):
pass
def handleIncomingMsg(self, data, socket,pid):
try:
print ('message received %s' %data)
#converts the unicode data that arrives into a dict
data = ast.literal_eval(data)
type = data['type']
except :
print ("Unexpected error:" + sys.exc_info()[0])
type = 'error'
print('except')
if type == "join":
#add to connection list
self.addToConnectionList(socket, data)
success = session.addPlayer(data['pid'])
if(success):
#self.sendMessage(data['pid'], "state", str(session.getState()) )
self.sendToAll("state", str(session.getState()) )
if type == "pieceMovement":
self.sendToAll(type,data);
#Adds new player to the list of connected players
def addToConnectionList(self, socket, message):
socket.id= message['pid']
connections[socket.id]=socket
print(str(socket.id) + " joined")
#add in types
def sendMessage(self,pid,type,data):
try:
msg=dict()
msg["type"]=type;
msg["data"]=data;
msg=json.dumps(msg)
connections[pid].write_message(msg)
except KeyError:
print("Player " + str(pid) + " isn't connected")
def sendToOtherPlayer(self,my_pid,type,data):
for pid in connections:
if my_pid != pid:
#print(my_pid )
#print(pid)
print(my_pid ,"Sent message to ",pid)
self.sendMessage(pid,type,data)
#Sends to all connected players
def sendToAll(self,type,data):
for pid in connections:
self.sendMessage(pid,type,data)
#needs to be after the class def
messageHandler = MessageHandler();
app= tornado.web.Application([
#map the handler to the URI named "wstest"
(r'/wstest', WSHandler),
])
if __name__ == '__main__':
app.listen(8080)
tornado.ioloop.IOLoop.instance().start()