Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Tree: 34d6d60927
Fetching contributors…

Cannot retrieve contributors at this time

65 lines (58 sloc) 2.054 kB
import tornado
from tornado import websocket
import json
import random
def random_board_state():
bs = {}
bs['tokens'] = {}
bs['tokens']['943'] = {
'id': '943',
'pos': {
'x': random.randint(0, 300),
'y': random.randint(0, 300),
}
}
bs['tokens']['345'] = {
'id': '345',
'pos': {
'x': random.randint(0, 300),
'y': random.randint(0, 300),
}
}
return bs
class EchoWebSocket(websocket.WebSocketHandler):
board_state = None
all_the_connections = []
def broadcast(self, msg):
for sock in EchoWebSocket.all_the_connections:
try:
sock.write_message(msg)
except IOError:
EchoWebSocket.all_the_connections.remove(sock)
def open(self):
self.tavishid = random.randint(0, 1000)
if EchoWebSocket.board_state is None:
EchoWebSocket.board_state = random_board_state()
json_msg = json.JSONEncoder().encode(EchoWebSocket.board_state)
EchoWebSocket.all_the_connections.append(self)
self.broadcast(json_msg)
print "WebSocket opened"
def on_message(self, message):
decoded_message = json.JSONDecoder().decode(message)
if decoded_message['id'] in EchoWebSocket.board_state['tokens'].keys():
EchoWebSocket.board_state['tokens'][decoded_message['id']]['pos'] = decoded_message['pos']
json_msg = json.JSONEncoder().encode(EchoWebSocket.board_state)
self.broadcast(json_msg)
#self.broadcast(u"You said: " + message + ("".join(EchoWebSocket.bla)))
def on_close(self):
print EchoWebSocket.all_the_connections
for sock in EchoWebSocket.all_the_connections:
if sock.tavishid == self.tavishid:
EchoWebSocket.all_the_connections.remove(self)
print "WebSocket closed"
application = tornado.web.Application([
(r"/", EchoWebSocket),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Jump to Line
Something went wrong with that request. Please try again.