def handle_join(new_tcp_sock, new_udp_sock, add_to_list=True): global clients global num_clients global client_id_inc c = Client() c.tcp_sock = new_tcp_sock c.udp_sock = new_udp_sock c.id = client_id_inc c.ip = new_tcp_sock.getpeername()[0] c.c_tcp_port = new_tcp_sock.getpeername()[1] c.s_tcp_port = new_tcp_sock.getsockname()[1] c.s_udp_port = new_udp_sock.getsockname()[1] c.callbacks = [] if (add_to_list): clients.append(c) debug.log( "accepted client (client-id: %d, ip: %s, c_tcp_port: %d, c_udp_port: %d, s_tcp_port: %d, s_udp_port: %d)" % (c.id, c.ip, c.c_tcp_port, c.c_udp_port, c.s_tcp_port, c.s_udp_port), debug.P_INFO) num_clients += 1 client_id_inc += 1 accounts.init_client_account(c) msg.send(c.tcp_sock, c, msg.build(_MID.SEND_SERVER_CONNECTION_ESTABLISHED_SUCCESSFULLY))
def client_join(self, client_obj): new_gcl = GameClient(); new_gcl.client_obj = client_obj; self.g_clients.append(new_gcl); client_obj.joined_game = self; client_obj.game_client = new_gcl; #self_peer = Peer(); #self_peer.game_client = new_gcl; #new_gcl.peers.append(self_peer); if (len(self.g_clients) >= 2): for gcl in self.g_clients: if (gcl != new_gcl): #send a bind request to all clients except the newly joined one msg.send(gcl.client_obj.tcp_sock, gcl.client_obj, msg.build(_MID.SEND_UDP_PEER_BIND_REQUEST, client_obj.id, client_obj.ip)); #add 1 new peer for the newly joined client joined_peer = Peer(); joined_peer.game_client = new_gcl; gcl.peers.append(joined_peer); print("added peer id %d to game client %d. peers len: %d" % (new_gcl.client_obj.id, gcl.client_obj.id, len(gcl.peers))); #send a bind request to the newly joined client for every other client in the game msg.send(client_obj.tcp_sock, client_obj, msg.build(_MID.SEND_UDP_PEER_BIND_REQUEST, gcl.client_obj.id, gcl.client_obj.ip)); #append the newly joined clients peer list with every other client in the game client_peer = Peer(); client_peer.game_client = gcl; new_gcl.peers.append(client_peer); print("2added peer id %d to game client %d. peers len: %d" % (gcl.client_obj.id, new_gcl.client_obj.id, len(new_gcl.peers)));
def main(): msg.init() while True: msg.send('M', 'Hello world!') m = msg.recv() print(m) time.sleep(1)
def handle_join(new_tcp_sock, new_udp_sock, add_to_list = True): global clients global num_clients global client_id_inc c = Client(); c.tcp_sock = new_tcp_sock; c.udp_sock = new_udp_sock; c.id = client_id_inc; c.ip = new_tcp_sock.getpeername()[0]; c.c_tcp_port = new_tcp_sock.getpeername()[1]; c.s_tcp_port = new_tcp_sock.getsockname()[1]; c.s_udp_port = new_udp_sock.getsockname()[1]; c.callbacks = []; if (add_to_list): clients.append(c); debug.log("accepted client (client-id: %d, ip: %s, c_tcp_port: %d, c_udp_port: %d, s_tcp_port: %d, s_udp_port: %d)" % (c.id, c.ip, c.c_tcp_port, c.c_udp_port, c.s_tcp_port, c.s_udp_port), debug.P_INFO); num_clients += 1; client_id_inc += 1; accounts.init_client_account(c); msg.send(c.tcp_sock, c, msg.build(_MID.SEND_SERVER_CONNECTION_ESTABLISHED_SUCCESSFULLY));
def received_udp_bind_port(self, game_client, peer_id, peer_ip, port): if (port >= 0): for p in game_client.peers: if (p.game_client.client_obj.id == peer_id and p.game_client.client_obj.ip == peer_ip): p.binded = True p.port = port print("peer id %d binded" % game_client.client_obj.id) all_binded = True for gcl in self.g_clients: for p in gcl.peers: if (p.binded == False): all_binded = False break if (all_binded): print("all binded, sending ping pong requests") for gcl in self.g_clients: for p in gcl.peers: pcl = p.game_client.client_obj msg.send( pcl.tcp_sock, pcl, msg.build(_MID.SEND_UDP_PEER_PORT, gcl.client_obj.id, p.port)) else: print("udp bind failed, dunno how to handle this right now")
def add(self, opts, f, controls): id = repr(f) iobj = { 'id': id, 'controls': [c.json_dict() for c in controls] } iobj.update(opts) self._interacts[id] = (f, controls) msg.send(msg.Interact(dict=iobj))
def main(): msg.init() debug("Spawned") while True: m = msg.recv() if m[0] == msg.DFileReq: [_, user, compid, request] = m fd = open("../../../test/webserver/" + request) msg.send(msg.DFileRes, user, compid, request, fd) else: debug("Unhandled message " + str(m)) debug(str(m))
def handle_udp_pong(message): if (message.callback_result == callback.CALLBACK_RESULT_TIMEOUT): message.client_obj.udp_timeout_tries += 1; if (message.client_obj.udp_timeout_tries >= 3): handle_leave(message.client_obj, "UDP ping pong timed out 3 times"); else: send_udp_ping(message.client_obj); else: print("udp ping pong success"); message.client_obj.udp_timeout_tries = 0; msg.send(message.client_obj.tcp_sock, message.client_obj, msg.build(_MID.SEND_SERVER_CONNECTION_ESTABLISHED_SUCCESSFULLY));
def main(): msg.init() debug("Spawned") m = msg.recv() if m[0] == msg.InitClient: rfile = m[1] wfile = m[2] else: debug("should have received InitClient message first") signal.signal(signal.SIGTERM, mkhandler(rfile, wfile)) rdy = [] while rdy == []: rdy, _, _ = select.select([rfile], [], []) data = rfile.readline() if data: req = HTTPRequest(rfile, data) if hasattr(req, 'path'): print('Resource: ' + req.path) msg.send(msg.FileReq, req.path) m = msg.recv() if m[0] == msg.FileRes: [_, name, fd] = m response = fd.read() contents = ( "HTTP/1.0 200 OK\r\n" + "Content-Length: " + str(len(response)) + "\r\n" + "Content-Type: text/html\r\n\r\n" + response ) debug("access to file " + name + " was authorized") wfile.write(contents) elif m[0] == msg.FileResF: debug("access to file " + m[1] + " was refused") response = "Access Forbidden" wfile.write( "HTTP/1.0 403 Forbidden\r\n" + "Content-Length: " + str(len(response)) + "\r\n" + "Content-Type: text/html\r\n\r\n" + response ) else: debug("unexpected message " + str(m)) debug('Shutting down') rfile.close() wfile.close() # YOU MUSTN'T DIE SOLDIER! while True: time.sleep(3600)
def handle_udp_pong(message): if (message.callback_result == callback.CALLBACK_RESULT_TIMEOUT): message.client_obj.udp_timeout_tries += 1 if (message.client_obj.udp_timeout_tries >= 3): handle_leave(message.client_obj, "UDP ping pong timed out 3 times") else: send_udp_ping(message.client_obj) else: print("udp ping pong success") message.client_obj.udp_timeout_tries = 0 msg.send( message.client_obj.tcp_sock, message.client_obj, msg.build(_MID.SEND_SERVER_CONNECTION_ESTABLISHED_SUCCESSFULLY))
def handle_all_messages(m): if (m.mid == _MID.RECV_CLIENT_ATTEMPT_REGISTER): result = db.add_user_account(m.params[0], m.params[1]); msg.send(m.sock, m.client_obj, msg.build(_MID.SEND_CLIENT_ATTEMPT_REGISTER_RESULT, result)); elif (m.mid == _MID.RECV_CLIENT_ATTEMPT_LOGIN): result, unique_id = db.find_user_account(m.params[0], m.params[1]); if (result == LoginResult.SUCCESS): acc_details = AccDetails(); acc_details.parent_client = m.client_obj; acc_details.unique_id = unique_id; m.client_obj.acc_details = acc_details; update_acc_details(m.client_obj, unique_id); t = time.time(); db.set_attrib(unique_id, "last_login_time", t); acc_details.last_login_time = t; result, total = db.get_attrib(unique_id, "total_login_time"); if (result == GeneralResult.SUCCESS): acc_details.total_login_time = total; msg.send(m.sock, m.client_obj, msg.build(_MID.SEND_CLIENT_ATTEMPT_LOGIN_RESULT, result)); elif (m.mid == _MID.RECV_REQUEST_FOR_CLIENT_ACCOUNT_DETAILS): acc_details = m.client_obj.acc_details; result = GeneralResult.ERROR; username = ""; gold = -1; if (acc_details and acc_details.parent_client == m.client_obj): result = GeneralResult.SUCCESS; username = acc_details.username; gold = acc_details.gold; msg.send(m.sock, m.client_obj, msg.build(_MID.SEND_CLIENT_ACCOUNT_DETAILS, result, username, gold)); elif (m.mid == _MID.RECV_REQUEST_TO_BUY_BOOSTER_PACK): acc_details = m.client_obj.acc_details; result = GeneralResult.UNKNOWN_ERROR; gold = -1; if (m.client_obj.acc_details != None): cost = 0; if (m.params[0] == 0): cost = 450; elif (m.params[0] == 1): cost = 800; elif (m.params[0] == 2): cost = 2000; if (cost != 0): gold = acc_details.gold - cost; if (gold >= 0): result = db.set_acc_gold(acc_details.unique_id, gold); if (result == GeneralResult.SUCCESS): acc_details.gold = gold; else: result = GeneralResult.ERROR; msg.send(m.sock, m.client_obj, msg.build(_MID.SEND_REQUEST_TO_BUY_BOOSTER_PACK_RESULT, result, gold));
def main(): msg.init() debug("Spawned") while True: m = msg.recv() s = str(m) try: if m[0] == msg.ACLoginReq: [_, user, password, compid, rfile, wfile] = m try: ok = password == credentials[user] except KeyError: ok = False if ok: debug(user + " logged in") debug("RFile: " + str(rfile)) debug("WFile: " + str(wfile)) msg.send(msg.ACLoginResT, user, compid, rfile, wfile) else: debug(user + " refused (wrong password)") msg.send(msg.ACLoginResF, user, compid) elif m[0] == msg.ACFileReq: [_, user, compid, request] = m try: ok = user in owners[request] except KeyError: ok = False if ok: debug(user + " access to " + request + " authorized") msg.send(msg.ACFileResT, user, compid, request) else: debug(user + " access to " + request + " refused") msg.send(msg.ACFileResF, user, compid, request) else: debug("Unhandled message " + s) except ValueError: debug("Unexpected payload " + s)
def main(): msg.init() debug("Spawned") m = msg.recv() if m[0] == msg.InitClient: rfile = m[1] wfile = m[2] else: debug("should have received InitClient message first") signal.signal(signal.SIGTERM, mkhandler(rfile, wfile)) rdy = [] while rdy == []: rdy, _, _ = select.select([rfile], [], []) data = rfile.readline() if data: req = HTTPRequest(rfile, data) if hasattr(req, 'path'): print('Resource: ' + req.path) msg.send(msg.FileReq, req.path) m = msg.recv() if m[0] == msg.FileRes: [_, name, fd] = m response = fd.read() contents = ("HTTP/1.0 200 OK\r\n" + "Content-Length: " + str(len(response)) + "\r\n" + "Content-Type: text/html\r\n\r\n" + response) debug("access to file " + name + " was authorized") wfile.write(contents) elif m[0] == msg.FileResF: debug("access to file " + m[1] + " was refused") response = "Access Forbidden" wfile.write("HTTP/1.0 403 Forbidden\r\n" + "Content-Length: " + str(len(response)) + "\r\n" + "Content-Type: text/html\r\n\r\n" + response) else: debug("unexpected message " + str(m)) debug('Shutting down') rfile.close() wfile.close() # YOU MUSTN'T DIE SOLDIER! while True: time.sleep(3600)
def handle_leave(client_obj, leave_msg, remove_from_list = True): global clients; global num_clients; client_obj.left = True; msg.send(client_obj.tcp_sock, client_obj, msg.build(_MID.SEND_CLIENT_LEAVE, leave_msg)); game.client_leave(client_obj); accounts.handle_client_leave(client_obj); client_obj.tcp_sock.close(); client_obj.udp_sock.close(); client_obj.callbacks = []; debug.log("client disconnected (client-id: %d, ip: %s, c_tcp_port: %d, c_udp_port: %d, s_tcp_port: %d, s_udp_port: %d, msg: %s)" % (client_obj.id, client_obj.ip, client_obj.c_tcp_port, client_obj.c_udp_port, client_obj.s_tcp_port, client_obj.s_udp_port, leave_msg), debug.P_INFO); if (remove_from_list): clients.remove(client_obj); client_obj = None; num_clients -= 1;
def client_join(self, client_obj): new_gcl = GameClient() new_gcl.client_obj = client_obj self.g_clients.append(new_gcl) client_obj.joined_game = self client_obj.game_client = new_gcl #self_peer = Peer(); #self_peer.game_client = new_gcl; #new_gcl.peers.append(self_peer); if (len(self.g_clients) >= 2): for gcl in self.g_clients: if (gcl != new_gcl): #send a bind request to all clients except the newly joined one msg.send( gcl.client_obj.tcp_sock, gcl.client_obj, msg.build(_MID.SEND_UDP_PEER_BIND_REQUEST, client_obj.id, client_obj.ip)) #add 1 new peer for the newly joined client joined_peer = Peer() joined_peer.game_client = new_gcl gcl.peers.append(joined_peer) print("added peer id %d to game client %d. peers len: %d" % (new_gcl.client_obj.id, gcl.client_obj.id, len(gcl.peers))) #send a bind request to the newly joined client for every other client in the game msg.send( client_obj.tcp_sock, client_obj, msg.build(_MID.SEND_UDP_PEER_BIND_REQUEST, gcl.client_obj.id, gcl.client_obj.ip)) #append the newly joined clients peer list with every other client in the game client_peer = Peer() client_peer.game_client = gcl new_gcl.peers.append(client_peer) print( "2added peer id %d to game client %d. peers len: %d" % (gcl.client_obj.id, new_gcl.client_obj.id, len(new_gcl.peers)))
def got_msg(sock, client_obj, byte_data): message = msg.extract_message(sock, client_obj, byte_data); if (message != None): mid = message.mid; params = message.params; np = len(params); msg.log(message); callback.process_message(message); return; if (verify_params(mid, _MID.RECV_CLIENT_REGISTER_USER_PASS, np)): print("username: %s, password: %s" % (params[0], params[1])); db.add_user_account(params[0], params[1]); elif (verify_params(mid, _MID.RELAY_TEST, np)): msg.send(sock, client_obj, msg.build(_MID.RELAY_TEST, client_obj.id, client_obj.ip, client_obj.c_tcp_port, client_obj.c_udp_port)); elif (verify_params(mid, _MID.SEND_CLIENT_ID, np)): pass; elif (verify_params(mid, _MID.RECV_CLIENT_BINDED_UDP_PORT, np)): client_obj.c_udp_port = params[0]; elif (verify_params(mid, _MID.RECV_UDP_PEER_BIND_PORT_SUCCESS, np)): client_obj.joined_game.received_udp_bind_port(client_obj.game_client, params[0], params[1], params[2]); elif (verify_params(mid, _MID.RECV_UDP_PEER_BIND_PORT_FAILED, np)): client_obj.joined_game.received_udp_bind_port(client_obj.game_client, params[0], params[1], -1); elif (verify_params(mid, _MID.RECV_PEER_CONNECT_SUCCESS, np)): client_obj.joined_game.received_connect_success(client_obj.game_client, params[0], params[1]); elif (verify_params(mid, _MID.BEGIN_RELAY_TEST, np)): msg.send(sock, client_obj, msg.build(_MID.RELAY_TEST, client_obj.id, client_obj.ip, client_obj.c_tcp_port, client_obj.c_udp_port)); else: print("received msg (raw: %s, len: %d) has an unknown MID" % (byte_data, byte_data.__len__()));
def received_udp_bind_port(self, game_client, peer_id, peer_ip, port): if (port >= 0): for p in game_client.peers: if (p.game_client.client_obj.id == peer_id and p.game_client.client_obj.ip == peer_ip): p.binded = True; p.port = port; print("peer id %d binded" % game_client.client_obj.id); all_binded = True; for gcl in self.g_clients: for p in gcl.peers: if (p.binded == False): all_binded = False; break; if (all_binded): print("all binded, sending ping pong requests"); for gcl in self.g_clients: for p in gcl.peers: pcl = p.game_client.client_obj; msg.send(pcl.tcp_sock, pcl, msg.build(_MID.SEND_UDP_PEER_PORT, gcl.client_obj.id, p.port)); else: print("udp bind failed, dunno how to handle this right now");
def handle_leave(client_obj, leave_msg, remove_from_list=True): global clients global num_clients client_obj.left = True msg.send(client_obj.tcp_sock, client_obj, msg.build(_MID.SEND_CLIENT_LEAVE, leave_msg)) game.client_leave(client_obj) accounts.handle_client_leave(client_obj) client_obj.tcp_sock.close() client_obj.udp_sock.close() client_obj.callbacks = [] debug.log( "client disconnected (client-id: %d, ip: %s, c_tcp_port: %d, c_udp_port: %d, s_tcp_port: %d, s_udp_port: %d, msg: %s)" % (client_obj.id, client_obj.ip, client_obj.c_tcp_port, client_obj.c_udp_port, client_obj.s_tcp_port, client_obj.s_udp_port, leave_msg), debug.P_INFO) if (remove_from_list): clients.remove(client_obj) client_obj = None num_clients -= 1
def updatechess(): # print ".", global g, prev_board, prev_arBoard for _ in range(100): gtk.main_iteration(block=False) # gtk.gdk.threads_enter() if g is None and i.globalgamemodel is not None: g = i.globalgamemodel board = g.boards[-1] msg.send("BEGIN:%s" % board.board.arBoard.tostring()) if g is not None: # print g.players, id(g.boards[-1]), g.boards[-1] board = g.boards[-1] if board is not prev_board: # print "BOARD:", board if len(board.board.history) > 0: prevmove = board.board.history[-1][0] parsemove.parsemove(board, prev_arBoard, prevmove) prev_board = board prev_arBoard = board.board.arBoard[:]
def updatechess(): #print ".", global g, prev_board, prev_arBoard for _ in range(100): gtk.main_iteration(block=False) #gtk.gdk.threads_enter() if g is None and i.globalgamemodel is not None: g = i.globalgamemodel board = g.boards[-1] msg.send("BEGIN:%s" % board.board.arBoard.tostring()) if g is not None: #print g.players, id(g.boards[-1]), g.boards[-1] board = g.boards[-1] if board is not prev_board: #print "BOARD:", board if len(board.board.history) > 0: prevmove = board.board.history[-1][0] parsemove.parsemove(board, prev_arBoard, prevmove) prev_board = board prev_arBoard = board.board.arBoard[:]
def removePiece(tcord, tpiece, opcolor): send("REMOVE:%d,%d,%d" % (tcord, tpiece, opcolor))
def movePiece(fcord, tcord, piece, color): send("MOVE:%d,%d,%d,%d" % (fcord, tcord, piece, color))
def click(self, x, y, button, press): if press: msg.send(msg.MouseClick, str(x), str(y), 1) else: msg.send(msg.MouseClick, str(x), str(y), 0)
def req_resource(self, uri): print "Requesting:", uri msg.send(msg.ReqResource, uri)
def send_udp_ping(client_obj): client_obj.add_message_handler(_MID.RECV_UDP_PONG, handle_udp_pong, callback.TIMEOUT_SHORT, True) msg.send(client_obj.udp_sock, client_obj, msg.build(_MID.SEND_UDP_PING))
def addPiece(tcord, piece, color): send("ADD:%d,%d,%d" % (tcord, piece, color))
def send_udp_ping(client_obj): client_obj.add_message_handler(_MID.RECV_UDP_PONG, handle_udp_pong, callback.TIMEOUT_SHORT, True); msg.send(client_obj.udp_sock, client_obj, msg.build(_MID.SEND_UDP_PING));
#!/usr/bin/env python2.7 import msg, socket, time import uuid HOST_NAME = 'localhost' # !!!REMEMBER TO CHANGE THIS!!! PORT_NUMBER = 9000 # Maybe set this to 9000. def debug(s): print(" L: " + s) if __name__ == '__main__': msg.init() debug("Spawned") s = socket.socket() try: s.bind((HOST_NAME, PORT_NUMBER)) print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER) while True: s.listen(0) (bs, addr) = s.accept() debug('Accepting: ' + str(addr)) msg.send(msg.LoginReq, 'default', ' ', str(uuid.uuid4()), bs, bs) except: s.close() print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
def render(self, x, y, width, height): self.shm_obj.write_webkit_as_png(x, y, width, height, self.browser) msg.send(msg.Display, str(self.shm_obj.get_shmid()))
def keyrelease(self, keysym) : msg.send(msg.KeyPress, str(keysym))
def keyrelease(self, keysym): msg.send(msg.KeyPress, str(keysym))
def handle_all_messages(m): if (m.mid == _MID.RECV_CLIENT_ATTEMPT_REGISTER): result = db.add_user_account(m.params[0], m.params[1]) msg.send(m.sock, m.client_obj, msg.build(_MID.SEND_CLIENT_ATTEMPT_REGISTER_RESULT, result)) elif (m.mid == _MID.RECV_CLIENT_ATTEMPT_LOGIN): result, unique_id = db.find_user_account(m.params[0], m.params[1]) if (result == LoginResult.SUCCESS): acc_details = AccDetails() acc_details.parent_client = m.client_obj acc_details.unique_id = unique_id m.client_obj.acc_details = acc_details update_acc_details(m.client_obj, unique_id) t = time.time() db.set_attrib(unique_id, "last_login_time", t) acc_details.last_login_time = t result, total = db.get_attrib(unique_id, "total_login_time") if (result == GeneralResult.SUCCESS): acc_details.total_login_time = total msg.send(m.sock, m.client_obj, msg.build(_MID.SEND_CLIENT_ATTEMPT_LOGIN_RESULT, result)) elif (m.mid == _MID.RECV_REQUEST_FOR_CLIENT_ACCOUNT_DETAILS): acc_details = m.client_obj.acc_details result = GeneralResult.ERROR username = "" gold = -1 if (acc_details and acc_details.parent_client == m.client_obj): result = GeneralResult.SUCCESS username = acc_details.username gold = acc_details.gold msg.send( m.sock, m.client_obj, msg.build(_MID.SEND_CLIENT_ACCOUNT_DETAILS, result, username, gold)) elif (m.mid == _MID.RECV_REQUEST_TO_BUY_BOOSTER_PACK): acc_details = m.client_obj.acc_details result = GeneralResult.UNKNOWN_ERROR gold = -1 if (m.client_obj.acc_details != None): cost = 0 if (m.params[0] == 0): cost = 450 elif (m.params[0] == 1): cost = 800 elif (m.params[0] == 2): cost = 2000 if (cost != 0): gold = acc_details.gold - cost if (gold >= 0): result = db.set_acc_gold(acc_details.unique_id, gold) if (result == GeneralResult.SUCCESS): acc_details.gold = gold else: result = GeneralResult.ERROR msg.send( m.sock, m.client_obj, msg.build(_MID.SEND_REQUEST_TO_BUY_BOOSTER_PACK_RESULT, result, gold))