def main(): done = False port = 8888 server = Listener(port, MyHandler) print ('Server started') print 'Server IP Address: ' + str(get_my_ip()) print 'type QUIT to end the server' while not done: input = sys.stdin.readline().rstrip() if 'QUIT' in input: for c in clients: c.do_send('!!QUIT!!') done = True server.stop() # cleanup sys.exit()
def build_las(x, y, char2idx, is_training=False): with tf.variable_scope('encoder'): encoder_output = Listener(x) with tf.variable_scope('decoder'): decoder_input = tf.concat((tf.ones_like(y[:, :1])*char2idx['S'], y[:, :-1]), -1) decoder_input = embed(decoder_input, len(hp.vocab), hp.las_embed_size, zero_pad=True) # double check logits, attention_weight = Speller(decoder_input, encoder_output, is_training=is_training) return logits, attention_weight
def start_server(): global server event_queue = [] # list of ('event', handler) port = 8888 server = Listener(port, Server) #server = Server() #start_thread() return server
def on_close(self): for name, h in handlers.items(): if h == self: del handlers[name] user = waiting.popleft() handlers[user[0]] = user[1] user[1].do_send(prompt) def on_msg(self, msg): if 'join' in msg: if len(handlers) >= 2: waiting.append((msg['join'], self)) self.do_send("Please wait for next available agent") else: handlers[msg['join']] = self self.do_send(prompt) else: if (msg['speak'], self) in waiting: self.do_send("Please wait for next available agent") else: for name in handlers.keys(): if name != msg['speak']: handlers[name].do_send(msg['speak'] + ": " + msg['txt']) port = 8888 server = Listener(port, MyHandler) while 1: poll(timeout=0.05) # in seconds
# easter egg elif (msg.get('txt') == ":e"): egg = '\n' + get_easter_egg(EASTER) self.do_send(egg) else: print("Client: " + msg.get('txt')) reply = raw_input("Reply: ") self._log.append("Agent: " + reply) self.do_send(reply) else: self.do_send("Agent is busy") def strlist_to_str(l): text = "" for s in l: text += s + "\n" return text if __name__ == '__main__': port = 8888 server = Listener(port, MyHandler) while True: poll(timeout=0.05) # in seconds server.stop()
from network import Listener, Handler, poll done = False class MyHandler(Handler): def on_open(self): print 'srv on open' def on_close(self): print 'srv on close' def on_msg(self, data): print 'srv received %s' % str(data) msg = {12: 3, 'hello': (1, 2)} self.do_send(msg) print 'srv sent %s' % str(msg) self.close_when_done() global done done = True port = 8888 server = Listener(port, MyHandler) while not done: poll(timeout=.1) server.stop() # cleanup
receive player inputs in JSON. """ def encode(self, msg): return base64.b64encode(zlib.compress(msg)) def on_open(self): event_queue.append(('join', self)) def on_close(self): event_queue.append(('quit', self)) def on_msg(self, data): event_queue.append((data['input'], self)) Listener(8888, MyHandler) ######################### loop ####################### def apply_client_events(): # apply events onto game state global event_queue for event, handler in event_queue: if event == 'quit': del players[handler] elif event == 'join': players[handler] = Player() else: # movement input players[handler].change_dir(event) event_queue = []
def __init__(self, mode="train"): # Load vocabulary self.char2idx, self.idx2char = load_vocab() # Set phase self.is_training = True if mode == "train" else False # Data Feeding # x: melspectrogram. (batch, T, n_mels) # y: Text. (N, Tx) if mode == "train": self.y, self.x, _, _, self.num_batch = get_batch() else: self.x = tf.placeholder(tf.float32, shape=(None, None, hp.n_mels)) self.y = tf.placeholder(tf.int32, shape=(None, None)) # Get encoder/decoder inputs with tf.variable_scope('encoder'): self.encoder_output = Listener(self.x) with tf.variable_scope('decoder'): self.decoder_input = tf.concat( (tf.ones_like(self.y[:, :1]) * self.char2idx['S'], self.y[:, :-1]), -1) self.decoder_input = embed(self.decoder_input, len(hp.vocab), hp.embed_size, zero_pad=True) self.logits, self.attention_weight = Speller( self.decoder_input, self.encoder_output, is_training=self.is_training) self.preds = tf.to_int32(tf.arg_max(self.logits, dimension=-1)) self.istarget = tf.to_float(tf.not_equal(self.y, self.char2idx['P'])) self.acc = tf.reduce_sum( tf.to_float(tf.equal(self.preds, self.y)) * self.istarget) / (tf.reduce_sum(self.istarget)) # Loss self.y_smoothed = label_smoothing( tf.one_hot(self.y, depth=len(self.char2idx))) self.loss = tf.nn.softmax_cross_entropy_with_logits( logits=self.logits, labels=self.y_smoothed) self.loss = tf.reduce_sum(self.loss * self.istarget) / (tf.reduce_sum( self.istarget)) # Training Scheme self.global_step = tf.Variable(0, name='global_step', trainable=False) self.lr = tf.placeholder(tf.float32, shape=()) self.lr = hp.lr #self.optimizer = tf.train.AdamOptimizer(learning_rate=self.lr) ## gradient clipping self.gvs = self.optimizer.compute_gradients(self.loss) self.clipped = [] for grad, var in self.gvs: grad = tf.clip_by_norm(grad, 5.) self.clipped.append((grad, var)) self.train_op = self.optimizer.apply_gradients( self.clipped, global_step=self.global_step) # Summary #tf.summary.scalar('{}/guided_attention_loss'.format(mode), self.guided_attn_loss) tf.summary.scalar('{}/loss'.format(mode), self.loss) tf.summary.scalar('{}/acc'.format(mode), self.acc) tf.summary.scalar('{}/lr'.format(mode), self.lr) #tf.summary.image("{}/attention".format(mode), tf.expand_dims(self.alignments, -1), max_outputs=1) self.merged = tf.summary.merge_all()
for ip_port in ip_ports: ip, port = str(ip_port).split(':') peer = Peer(ip, int(port)) peer.ip_port = ip_port peer.do_send({'mtype': 'join', 'ip_port': MY_IP_PORT}) # Send the IP and port I will be listening to. # Receive in response the list of (IP, port) of peers in the network. dir_client = DirectoryClient(DIRECTORY_HOST, 8888) # async connect dir_client.do_send({'mtype': 'join_dir', 'ip_port': MY_IP_PORT}) while not dir_client.directory_received: poll(timeout=.1) # seconds print 'Retrieved a directory of %d peers.' % len(peers) # Listen to incoming P2P connections from future peers. p2p_listener = Listener(MY_PORT, Peer) ################### loop ################ TICK_DURATION = 0.02 # seconds while 1: loop_start = time.time() process_inputs() update_me() broadcast({'mtype': 'position', 'box': mybox}) draw_everything() poll_for(TICK_DURATION - (time.time() - loop_start)) # poll until tick is over
'size': [w, h] }) elif msgtype == 'eat_player': # grow the big by the size of the small small = players[data['target']] players[self.myname][2] += small[2] players[self.myname][3] += small[3] broadcast({ 'msg_type': 'grow', 'name': self.myname, 'size': [players[self.myname][2], players[self.myname][3]] }) elif msgtype == 'die': # back to normal size and place me randomly players[self.myname] = [randint(0, 280), randint(0, 280), 10, 10] broadcast({ 'msg_type': 'die', 'name': self.myname, 'state': players[self.myname] }) server = Listener(8888, MyHandler) # loop while 1: poll() sleep(.05) # seconds
def serverInstantiate(self): self.server = Listener(Model.port, MyHandler)
class TempServer(Handler): def on_open(self): print "connection attempted" event_queue.append(('join', self)) def on_close(self): print "close" event_queue.append(('quit', self)) def on_msg(self, msg): event_queue.append((msg['input'], self)) server = Listener(8888, TempServer) global board board = Board(900, 600, 6, 6, 5) global lobby lobby = Lobby(900, 600) while 1: # enqueue the player events received by the client handlers poll() # apply events onto game state for event, handler in event_queue: if event == 'quit':
handler.do_send("Now connecting to an agent.\n") handler.do_send({'type': "agent-connect", "address":agentAddress}) def set_free(self): #sets agent free global agent_free agent_free = True def _check_waiting(self): #checks to see if there are any clients waiting if len(client_handlers) > 0: global client_msgs self._check_agent(client_msgs.popleft()) server = Listener(SERVER_PORT, MyHandler) while 1: try: poll(timeout=0.05) # in seconds except: if agent_handler: agent_handler.do_send("Server Disconnected... Now Closing") agent_handler.do_send({"kill":""}) agent_handler.close() if current_handler: current_handler.do_send("Server Disconnected... Now Closing") current_handler.do_send({"kill":""}) current_handler.close() for handler in client_handlers: handler.do_send("Server Disconnected... Now Closing")