def detectInputKey(): dev = InputDevice('/dev/input/event4') while True: select([dev], [], []) for event in dev.read(): res=[event.code, event.value] return res
def receive(): global ack_dup global sndW global last_ack global fastretrans inf, outf, errf = select([Socket, ], [], [], 0) while inf: data, SNDADDR = Socket.recvfrom(1024) seg = tr_seg(data) senderLog.writelines("rcv %2.3f A %8d %3d %8d \n" % (time.time() % 1*10, seg.seq_num, len(seg.data), seg.ack_num)) if last_ack == seg.ack_num: ack_dup += 1 fastretrans += 1 if fastretrans >= 3: fastretrans = 0 return "FR", 0 else: fastretrans = 0 last_ack = seg.ack_num for j in sndW: if seg.ack_num == j.seq_num + len(j.data): sndW = sndW[sndW.index(j) + 1:] freeW() return "FW", 0 inf, outf, errf = select([Socket, ], [], [], 0) for i in sndW: if i.send_time: if time.time() > i.send_time + timeout/1000: return "TO",i return "NA",0
def receive(self): while self.active: (rlist, wlist, elist) = select([self.workSocket], [], [], self.select_timeout) if (len(rlist) > 0): # message arrived, read it break # message take 4 bytes, but only use the leading 2 bytes data = self.workSocket.recv(2) if (data == ""): # socket has broken raise ValueException('socket has broken') msgLen = ord(data[0]) * 256 + ord(data[1]) curLen = 0 msg = "" startT = time.time() while (self.active and (curLen < msgLen)): t = time.time() if (t - startT > self.receive_timeout): break (rlist, wlist, elist) = select([self.workSocket], [], [], self.select_timeout) if (len(rlist) == 0): # not ready yet, continue looping continue curMsg = self.workSocket.recv(msgLen - curLen) if (curMsg == None): # socket has broken raise ValueExceptino('socket has broken') msg += curMsg curLen += len(curMsg) return msg
def loop(self): global run while True: infds,outfds,errfds = select([self.serverObj,],[],[],5) if(run == 0): print 'close' #connection.close() self.serverObj.close() sys.exit() break if len(infds) != 0: connection, address = self.serverObj.accept() infds_c,outfds_c,errfds_c = select([connection,],[],[],3) print 'Server Connected by: ', address if len(infds_c) != 0: buf = connection.recv(8196) if len(buf) != 0: print str(buf) print address self.queue.put(str(address[0])) self.queue.put(str(address[1])) self.queue.put(str(buf)) connection.send('Echo:' + buf) connection.close()
def attente_joueur(self): """ Toutes les 0.05 secondes, accepte les connexions et vérifie si un joueur n'a pas demandé que la partie commence """ self.connexion.listen(5) print("On attends les clients") partie_commencee = False while not partie_commencee: # On va vérifier que de nouveaux clients ne demandent pas à se connecter connexions_demandees, wlist, xlist = select([self.connexion], [], [], 0.05) # On ajoute les sockets connectés à la liste des clients et on lui donne son ID for con in connexions_demandees: connexion_avec_client, infos_connexion = con.accept() # On ajoute le joueur self._map.ajouter_joueur(connexion_avec_client) # On prévient les autres joueurs sleep(2) msg = "{} autres joueurs\nAppuyez sur c pour commencer !".format( self._map.nb_joueurs - 1) self._map.prevenir_joueurs("Msg", msg) # On vérifie qu'il n'y a pas le maximum de joueurs (4) partie_commencee = self._map.nb_joueurs > nb_max_joueurs - 1 if partie_commencee: sleep(1) self._map.prevenir_joueurs( "Msg", "La partie commence !\nAttendez votre tour") # Maintenant, on écoute la liste des clients connectés clients_a_lire = [] try: clients_a_lire, wlist, xlist = select(self._map.sockets, [], [], 0.05) except: pass for client in clients_a_lire: # Réception du message try: msg_recu = client.recv(1024).decode() except (ConnectionResetError, ConnectionAbortedError): print( "Un joueur est parti, veuillez redémarrer le serveur.") self.terminer( "Un joueur est parti ou\nle serveur rencontre un problème.\nVous pouvez quitter" ) if controler_partie_commencee(msg_recu): partie_commencee = True self._map.prevenir_joueurs("Msg", "La partie commence !")
def send(self, data): """ Send data to the remote destination. Data may be of arbitrary length and should be split into smaller packets. This call should block for flow control, though you can buffer some small amount of data. This call should behave like `sendall` in Python; i.e., all data must be sent. Does not return any value. Should be called on a socket after connect or accept """ """ add data to send buffer """ # length_buffered = 0 start_seq = self.seq_number #print("IN SEND") while len(data) != 0: if len(data) > __MSS__: send_data = data[:__MSS__] data = data[__MSS__:] else: send_data = data data = b'' packet = MSG(__DATA_PACKET__, self.seq_number, 0, send_data) packet.encode_packet() self.send_buffer[self.seq_number] = packet self.send_length[self.seq_number] = packet.length while True: if self.rwnd > self.cwnd: upper_bound = self.cwnd + self.data_acked else: upper_bound = self.rwnd + self.data_acked if packet.length + self.data_sent <= upper_bound: break self.data_sent += packet.length r = [self.socket] w = [self.socket] e = [self.socket] readable, writeable, exceptions = select(r, w, e) while self.socket not in writeable: readable, writeable, exceptions = select(r, w, e) self.lock.acquire() send_time = time.time() data_sent = self.socket.sendto(packet.packet, self.target) self.lock.release() end_time = time.time() self.send_time[self.seq_number] = send_time self.seq_number += 1
def attente_joueur(self): """ Toutes les 0.05 secondes, accepte les connexions et vérifie si un joueur n'a pas demandé que la partie commence """ self.connexion.listen(5) print("On attends les clients") partie_commencee = False while not partie_commencee: # On va vérifier que de nouveaux clients ne demandent pas à se connecter connexions_demandees, wlist, xlist = select([self.connexion], [], [], 0.05) # On ajoute les sockets connectés à la liste des clients et on lui donne son ID for con in connexions_demandees: connexion_avec_client, infos_connexion = con.accept() # On ajoute le joueur self._map.ajouter_joueur(connexion_avec_client) # On prévient les autres joueurs sleep(2) msg = "{} autres joueurs\nAppuyez sur c pour commencer !".format(self._map.nb_joueurs - 1) self._map.prevenir_joueurs("Msg", msg) # On vérifie qu'il n'y a pas le maximum de joueurs (4) partie_commencee = self._map.nb_joueurs > nb_max_joueurs - 1 if partie_commencee: sleep(1) self._map.prevenir_joueurs("Msg", "La partie commence !\nAttendez votre tour") # Maintenant, on écoute la liste des clients connectés clients_a_lire = [] try: clients_a_lire, wlist, xlist = select(self._map.sockets, [], [], 0.05) except: pass for client in clients_a_lire: # Réception du message try: msg_recu = client.recv(1024).decode() except (ConnectionResetError, ConnectionAbortedError): print("Un joueur est parti, veuillez redémarrer le serveur.") self.terminer("Un joueur est parti ou\nle serveur rencontre un problème.\nVous pouvez quitter") if controler_partie_commencee(msg_recu): partie_commencee = True self._map.prevenir_joueurs("Msg", "La partie commence !")
def poll(self): if not self.sockets: return ([], [] ,[]) try: return select(self.sockets, self.output, [], 0.1) except error: inputs = [] outputs = [] errors = [] for s in self.sockets: try: select([s], [s], [], 0.01) except: errors.append(s) self.unregister(s) inputs, outputs, _ = select(self.sockets, self.output, [], 0.1) return inputs, outputs, errors
def manageConn(wrcht1, wrcht2, wait=None): """ manageCommand() handles I/O with a child process wrcht1 and wrcht2 are wratchet objects which implement both sides of this communication. formerly: cmd == command to be executed fin == "stdin" equivalent for cmd. This will be read from fout == "stdout" equivalent for cmd. This will be written to """ try: tmp = None idle = 0 while (True): ### socket input handling ### if (wrcht1.select()): idle = 0 tmp = wrcht1.recv() if (len(tmp) == 0): break if (VERYVERBOSE): sys.stderr.write("sckt: len: %d\n%s" % (len(tmp), tmp)) wrcht2.send(tmp) ### command input handling ### if (wrcht2.select()): idle = 0 tmp = wrcht2.recv() if (VERYVERBOSE): sys.stderr.write("cmd: len: %d\n%s" % (len(tmp), tmp)) if (len(tmp) == 0): break wrcht1.send(tmp) idle += 1 if (wait and idle > (wait * 10)): break select([], [], [], .1) except: print >> sys.stderr, ("Score!!") try: sys.excepthook(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]) wrcht1.close() wrcht2.close() except: pass sys.excepthook(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
def main_loop(): data = input(">> ") read, write, error = select([], [sock], [], 0) if len(write): b = sock.send(str.encode(data)) # receive while True: read, write, error = select([sock], [], [], 1) if len(read): data = bytes.decode(sock.recv(1024)) print(data) else: break
def mselect(rlist, wlist, xlist, xtimeout): """ # Description: A select() wrapper that compensates for platform # peculiarities. """ if xtimeout > 0 and sys.platform == 'MSWin32': # On windows, select() doesn't process the message loop, # but sleep() will, allowing alarm() to interrupt the latter. # So we chop up the timeout into smaller pieces and interleave # select() and sleep() calls. xt = xtimeout xgran = 0.5 # polling granularity in seconds args = (rlist, wlist, xlist) while True: if xgran > xt: xgran = xt xnfound = select(rlist, wlist, xlist, xgran) if xnfound == -1: break xt -= xgran if xnfound or xt <= 0: break sleep(0) rlist, wlist, xlist = args else: xnfound = select.select(rlist, wlist, xlist, xtimeout) return xnfound if xnfound != -1 else None
def start(self): self.sockfd.listen(5) self.rlist.append(self.sockfd) while True: rs, ws, xs = select(self.rlist, self.wlist, self.xlist) for fd in rs: if fd == self.sockfd: connfd, addr = fd.accept() print("Connect from:", addr) # 设置非阻塞 connfd.setblocking(False) self.rlist.append(connfd) else: msg = fd.recv(1024).decode() print(msg) if not msg: fd.close() self.rlist.remove(fd) request = msg.split("-") if request[0] == "R": self.register_user(fd, request[1], request[2]) elif request[0] == "L": self.log_in(fd, request[1], request[2]) elif request[0] == "S": self.search_wordmean(fd, request[1], request[2]) elif request[0] == "H": self.search_history(fd, request[1])
def get_eeprom_data(self, port): (ctlid, devid) = self.fiber_mapping[port] offset = (128 if port in self.qsfp_ports else 0) r_sel = [self.udpClient] req = struct.pack('=HHHBBHIBBBBI', 0, 9, 16, # lchip/msgtype/msglen ctlid, # uint8 ctl_id devid, # uint8 slave_dev_id 0x50, # uint16 dev_addr (1<<devid), # uint32 slave_bitmap offset, # uint8 offset 95, # uint8 length 0xf, # uint8 i2c_switch_id 0, # uint8 access_switch 95 # uint32 buf_length ) self.udpClient.sendto(req, ('localhost', 8101)) result = select(r_sel, [], [], 1) if self.udpClient in result[0]: rsp, addr = self.udpClient.recvfrom(1024) if rsp: rsp_data = struct.unpack('=HHHBBHIBBBBIi512B', rsp) if rsp_data[12] != 0: return None if port in self.qsfp_ports: return buffer(bytearray([0]*128), 0, 128) + buffer(rsp, 26, 512) return buffer(rsp, 26, 512) return None
def _serve(self, select=select.select): self._server.listen(16) try: while not self._stop.is_set(): r, w, x = select(self._reads, self._writes, self._reads, self._dispatch_event()) for s in r: if s is self._server: self._reads.add(self._accept()) else: self._nonblock_read(s) for client in w: self._nonblock_write(client) for s in x: s.close() if s is self._server: raise RuntimeError('Server is in exceptional condition') else: self._clean_up_client(s) finally: self.on_shutdown() for client in self._clients: self._clean_up_client(client, True) self._server.close()
def poll(*param): global libserial global QUIT seri_f = param[0] rlist = [seri_f] wlist = [] xlist = [] time = None rbuf = create_string_buffer(PACKSIZE) alldata = [] while not QUIT: (rlist, wlist, xlist) = select(rlist, wlist, xlist, time) for i in rlist: #接收并处理串口数据 if i == seri_f: rsize = libserial.ReadData( seri_f, byref(rbuf), c_int(PACKSIZE)) if rsize <= 0: QUIT = True alldata.extend([ord(i) for i in rbuf.raw[:rsize]]) #print "alldata: ", alldata if len(alldata) >= 8: alldata = proce_data(alldata)
def server(): server_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_sock.bind((HOST, PORT)) SOCKET_LIST.append(server_sock) print("starting time is: ", ctime()) print("server chat is innitilizing in port :" + str(PORT)) while 1: now, hey, error = select(SOCKET_LIST, [], []) for sock in lettore: if sock == server_sock: conn, address, =server_sock.accept() SOCKET_LIST.append(conn) print("1l client (%s, %s) si e comence" % address) transmission(server_sock, conn, "[%s, %s] >> entrato $ my chat room\n") else: try: data = sock_recv(RECV_BUFFER) if data: transmission(server_sock, sock, "\r" + str(sock.getpeername()) +"> "+ data) else: if sock in SOCKET_LIST: SOCKET_LIST.remove(sock) transmission(server_sock, sock, "its client (%s, %S)e' uscito....\n" % address) except: transmission(server_sock, sock, "its client (%s, %S)e' uscito....\n" % address) continue server_sock.close()
def main(): s = socket() s.bind(ADDR) s.listen() s.setblocking(False) rlist = [s] wlist = [] xlist = [] while True: rs, ws, xs = select(rlist, wlist, xlist) for i in rs: if i is s: connfd, addr = i.accept() print("Connect from", addr) connfd.setblocking(False) rlist.append(connfd) else: data = i.recv(1024).decode() if not data: rlist.remove(i) i.close() continue print(data) i.send(b"OK")
def mselect (rlist, wlist, xlist, xtimeout): """ # Description: A select() wrapper that compensates for platform # peculiarities. """ if xtimeout > 0 and sys.platform == 'MSWin32': # On windows, select() doesn't process the message loop, # but sleep() will, allowing alarm() to interrupt the latter. # So we chop up the timeout into smaller pieces and interleave # select() and sleep() calls. xt = xtimeout xgran = 0.5 # polling granularity in seconds args = (rlist, wlist, xlist) while True: if xgran > xt: xgran = xt xnfound = select(rlist, wlist, xlist, xgran) if xnfound == -1: break xt -= xgran if xnfound or xt <= 0: break sleep(0) rlist, wlist, xlist = args else: xnfound = select.select(rlist, wlist, xlist, xtimeout) return xnfound if xnfound != -1 else None
def dealRequest(self): while True: r_list, w_list, e_list = select(self.sk, [], [], 1) for s in r_list: conn, addr = s.accept() data = conn.recv(1024) # data is of type "action lock_name client_id" (e.g. "PREEMPT/RELEASE lock1 23", "UPDATEMAP 2") request = data.split(' ') if len(request) == 3: action = request[0] lock_name = request[1] client_id = int(request[2]) flag = self.check(lock_name, client_id) # "action lock_name client_id status" if flag == 0 && flag == 1: # The lock exists but doesn't belong to the client, please wait and try again. # The lock exists and already belongs to the client. conn.sendall(bytes(request[0] + " " + request[1] + " " request[2] + " 0")) elif flag == 2: self.updateMap(action, lock_name, client_id) # "PREEMPT": The lock has changed and now belongs to the client. # "RELEASE": The lock has released. self.sendUpdateCommand(request) # send a broadcast to all followers elif len(request) == 2 && request[0] == "UPDATEMAP": request_ver = int(request[1]) if self.map_ver != request_ver: conn.sendall(bytes(request[0] + " " + str(self.map_ver) + " " + str(self.lock_map))) else: # Your lock map is already up-to-date. conn.sendall(bytes(request[0] + " " + str(self.map_ver) + " Yes")) else: raise ValueError conn.close()
def run(self): """ Listen for incoming connections on PORT. When a connection is recieved, send a 302 redirect and then close the socket. """ # Accept an incoming connection. conn = select([self.listener], [], [], 0.1)[0] if conn: socket, address = self.listener.accept() conn = Connection(socket, address) # burn some time so that the client and server don't have a timing error trash = conn.socket.recv(1024) # send our https redirect conn.sendline("HTTP/1.1 302 Encryption Required") conn.sendline("Location: " + TARGET) conn.sendline("Connection: close") conn.sendline("Cache-control: private") conn.sendline("") conn.sendline( "<html><body>Encryption Required. Please go to <a href='" + TARGET + "'>" + TARGET + "</a> for this service.</body></html>") conn.sendline("") # kick em out conn.socket.close
def start(): global actual_price srv = socket(AF_INET, SOCK_STREAM) srv.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) srv.bind(("localhost", 55555)) srv.listen() sockets = [srv] pl = socket(AF_INET, SOCK_DGRAM) while actual_price < 1000000: readable, _, _ = select(sockets, [], [], 1) for active in readable: if active == srv: cli, addr = active.accept() print("New client connected ", addr) sockets.append(cli) else: msg = active.recv(1000) if not msg: active.close() sockets.remove(active) print("Client left") else: process_message(msg, active, pl)
def main(): inputIndex() if not os.path.exists("results"): os.makedirs("results") ret() #parsehtml() getval() while True: print("""1.Compute average 2.Compare with max and average 3.Quit""") rlist, _, _ = select([sys.stdin], [], [], timeout) if(rlist): sel=sys.stdin.readline() else: print "Time out exiting" break #sel=raw_input("Select an Analysis\n") if sel=="1": asys.Compavg() elif sel=='2': asys.compSub() elif sel=='3': print("Exiting") break shutil.rmtree('results') return 0
def __select_server(self): rs, ws, xs = select(self.__rlist, self.__wlist, self.__xlist) for item in rs: if item is self.__tcp_socket: self.__socket_connect() else: self.__server_handler(item)
def receive(port): input_buffer = 4096 sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind(("0.0.0.0",port)) sock.listen(10)' connection_list.append(sock) while 1: read_sockets,write_sockets,error_sockets=select(connection_list,[],[]) for s in read_sockets: if s == sock: sockfd,addr=sock.accept() connection_list.append(sockfd) send("Sending message to %s\n" %addr, sockfd) else: try: data=s.recv(input_buffer) if data: send(data,s) except: send(data,s) s.close() connection_list.remove(s) continue sock.close()
def _receive_action(self): """ Attends de recevoir une action correcte du joueur courant """ while True: clients_a_lire = [] try: clients_a_lire, wlist, xlist = select(self._map.sockets, [], [], 0.05) except: pass for client in clients_a_lire: # Réception du message try: msg_recu = client.recv(1024).decode() # Si un des client est parti except (ConnectionResetError, ConnectionAbortedError): print("Un joueur est parti, veuillez redémarrer le serveur.") self.terminer("Un joueur est parti ou\nle serveur rencontre un problème.\nVous pouvez quitter") type_ = controler_entree_client(msg_recu, self.joueur_courant) if type_ == None: continue return type_
def Start(self): self.tcpsock.bind(self.addr) self.tcpsock.listen(3) self.udpsock.bind(self.addr) connlist = [] while 1: selectList = [] selectList.append(self.tcpsock) selectList.append(self.udpsock) for con in connlist: selectList.append(con) results = select(selectList, [], []) for con in connlist: if results[0].count(con) is not 0: print "closing connection" con.close() connlist.remove(con) if results[0].count(self.tcpsock) is not 0: print "incomming connection" consoc, conaddr = self.tcpsock.accept() connlist.append(consoc) if results[0].count(self.udpsock) is not 0: print "incomming udp packet" data, addr = self.udpsock.recvfrom(self.buf) print data for sock in connlist: sock.send(data)
def run(self): '''Listens for incomming connections and creates threads (for the clients) accordingly.''' global LISTEN #Call the open_server_socket and set start variables. self.open_server_socket() input = [self.server, sys.stdin] #Print out console information sys.stdout.write("Waiting for connections.\n") while(LISTEN): ready_for_input, ready_for_output, ready_for_except = select(input, [], []) for s in ready_for_input: #If input comes from a connection: if s == self.server: #Create a client on an incoming connection client = Client(self.server.accept(), self.request_list) #Print out console information sys.stdout.write("Server: A connection has been established\n") #Start the thread client.start() #Append the thread to a list of threads self.threads.append(client) #If input comes from the server console: elif s == sys.stdin: #Terminate the server sys.stdout.write("Server terminated") LISTEN = False #Close down all the threads self.server.close() for c in self.threads: c.join()
def reporter_wait(s, wait_time=3): r, w, x = select([s], [], [], wait_time) if len(r) != 1: return "" else: return reporter_recv(s)
def start_socket_server(): HOST = '' PORT = 35520 BUFSIZE = 1024 ADDR = (HOST, PORT) serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(ADDR) serverSocket.listen(5) connection_list = [serverSocket] global tasks while True: try: print '# start: socket server' read_socket, write_socket, error_socket = select( connection_list, [], [], 5) for sock in read_socket: if sock == serverSocket: clientSocket, addr_info = serverSocket.accept() connection_list.append(clientSocket) else: data = sock.recv(BUFSIZE) if (not data): connection_list.remove(sock) sock.close() continue task = json.loads(data) tasks.append(task) except KeyboardInterrupt: serverSocket.close()
def RunCommandChannel(session, channel): global running global readFds readFds = [] readFds.append(channel) while running: result = select(readFds,[], []) for fd in range(len(result[0])): if result[0][fd] == channel: data = channel.recvfrom(500) command = data[0] if command[len(command)-1] == '\n': command = command[:len(command)-1] cmdOut = ProcessCommand(session, command) if cmdOut[0] == 0: running = 0 try: outMsg = "[%s]\n%s\n"%(command,cmdOut[1]) channel.sendto(outMsg, data[1]) except: pass channel.close()
def connect_handle(): HOST = 'localhost' PORT = 12345 ADDR = (HOST, PORT) server_sock.bind(ADDR) server_sock.listen(10) connection_list = [server_sock] print('Server started') while connection_list: try: print('Waiting for client') # select 로 요청을 받고, 10초마다 블럭킹을 해제하도록 함 read_socket, write_socket, error_socket = select(connection_list, [], [], 10) for sock in read_socket: # 새로운 접속 if sock == server_sock: client_sock, addr = server_sock.accept() connection_list.append(client_sock) t2 = Thread(target=client_handle, args=(client_sock,)) t2.daemon = True t2.start() except: break
def do_call(self): call = self.packer.get_buf() self.sock.send(call) try: from select import select except ImportError: print 'WARNING: select not found, RPC may hang' select = None BUFSIZE = 8192 # Max UDP buffer size timeout = 1 count = 5 while 1: r, w, x = [self.sock], [], [] if select: r, w, x = select(r, w, x, timeout) if self.sock not in r: count = count - 1 if count < 0: raise RuntimeError, 'timeout' if timeout < 25: timeout = timeout *2 ## print 'RESEND', timeout, count self.sock.send(call) continue reply = self.sock.recv(BUFSIZE) u = self.unpacker u.reset(reply) xid, verf = u.unpack_replyheader() if xid <> self.lastxid: ## print 'BAD xid' continue break
def loop(self): while True: # sockets to select for reading: (the server socket + every open # client connection) rlist = [self.ss] + list(self.clients) # sockets to select for writing: (those that have something in # bufout) wlist = [sock for sock in self.clients if len( self.clients[sock].bufout) > 0] (rl, wl, xl) = select(rlist, wlist, rlist) # Deal with incoming data: for s in rl: if s is self.ss: self.accept() elif s in self.clients: self.flushin(s) else: log(logging.ERROR, "Incoming, but %s not in clients anymore" % s) # Deal with outgoing data: for s in wl: if s in self.clients: self.flushout(s) else: log(logging.ERROR, "Outgoing, but %s not in clients anymore" % s) for s in xl: log(logging.ERROR, "EXCEPTION in %s. Closing" % s) self.delClient(s)
def receive(self, rcvSocket): messageHead = rcvSocket.recv(self.messageHeadLen) if (messageHead == ""): # socket has broken raise ValueError('socket has broken') msgLen = self.unpackMessageHead(messageHead) curLen = 0 msg = "" startT = time.time() while (self.active and (curLen < msgLen)): t = time.time() if (t - startT > self.receive_timeout): # timeout, discard this message self.logIncomingMessage("!!!!!!!! receive time out !!!!!!!!!") return (rlist, wlist, elist) = select([rcvSocket], [], [], self.select_timeout) if (len(rlist) == 0): # not ready yet, continue looping continue curMsg = rcvSocket.recv(msgLen - curLen) if (curMsg == None): # socket has broken raise ValueExceptino('socket has broken') msg += curMsg curLen += len(curMsg) self.logIncomingMessage(messageHead + msg) # send to the switch queue if exist if (self.switch != None): self.switch.addMessage(msg, None)
def server_run(): s = connect() inputs.append(s) while (1): r, w, e = select(inputs, [], []) for temp in r: if temp == s: new(s) else: disconnect = False try: data = temp.recv(1024).decode("utf-8") if data.strip() == 'show list': nameList = "%d people in talking room,these are %s" % ( len(names), who_in_room(names)) temp.send(nameList.encode("utf-8")) break data = names[temp] + ' say:' + data except error: data = names[temp] + ' say:' + 'leave the room' disconnect = True if (disconnect): inputs.remove(temp) print(data) for other in inputs: if other != s: other.send(data.encode("utf-8")) del names[temp] else: print(data) for other in inputs: if other != s: other.send(data.encode("utf-8"))
def getch(self): if select([self.file],[],[],0)[0]: c=self.file.read(1) c='2' else: c='1' return c
def RunCommandChannel(session, channel): global running global readFds readFds = [] readFds.append(channel) while running: result = select(readFds, [], []) for fd in range(len(result[0])): if result[0][fd] == channel: data = channel.recvfrom(500) command = data[0] if command[len(command) - 1] == '\n': command = command[:len(command) - 1] cmdOut = ProcessCommand(session, command) if cmdOut[0] == 0: running = 0 try: outMsg = "[%s]\n%s\n" % (command, cmdOut[1]) channel.sendto(outMsg, data[1]) except: pass channel.close()
def get_incoming_messages(self): to_read, to_write, err = select(self._listeningSockets, [], self._listeningSockets, 1) #could be a possible error here, need to purge from all room lists for sock in err: addr = sock.getpeername() self.remove_client(addr[1]) self._lobby.remove(sock) self._listeningSockets.remove(sock) for sock in to_read: try: buf = sock.recv(1024) except: print 'breaking in get_incoming connection due to exception' break if buf:#without this empty string was going into buffer self._in_buffer.append(buf) while self.get_ready_msgs(): pass #need to figure out how to get rid of the extra spaces while self._out_buffer: self.parse_message(self._out_buffer[0].strip()) del self._out_buffer[0]
def get_eeprom_data(self, port): (ctlid, devid) = self.fiber_mapping[port] offset = (128 if port in self.qsfp_ports else 0) r_sel = [self.udpClient] req = struct.pack( '=HHHBBHIBBBBI', 0, 9, 16, # lchip/msgtype/msglen ctlid, # uint8 ctl_id devid, # uint8 slave_dev_id 0x50, # uint16 dev_addr (1 << devid), # uint32 slave_bitmap offset, # uint8 offset 95, # uint8 length 0xf, # uint8 i2c_switch_id 0, # uint8 access_switch 95 # uint32 buf_length ) self.udpClient.sendto(req, ('localhost', 8101)) result = select(r_sel, [], [], 1) if self.udpClient in result[0]: rsp, addr = self.udpClient.recvfrom(1024) if rsp: rsp_data = struct.unpack('=HHHBBHIBBBBIi512B', rsp) if rsp_data[12] != 0: return None if port in self.qsfp_ports: return buffer(bytearray([0] * 128), 0, 128) + buffer( rsp, 26, 512) return buffer(rsp, 26, 512) return None
def loop(self): while True: # sockets to select for reading: (the server socket + every open client connection) rlist = [self.ss] + self.clients.keys() # sockets to select for writing: (those that have something in bufout) wlist = [ sock for sock in self.clients if len(self.clients[sock].bufout) > 0 ] logging.debug("select waiting for %dR %dW %dX", len(rlist), len(wlist), len(rlist)) (rl, wl, xl) = select(rlist, wlist, rlist) logging.debug("select: %s %s %s", rl, wl, xl) # Deal with incoming data: for s in rl: if s is self.ss: self.accept() elif s in self.clients: self.flushin(s) else: logging.error("Incoming, but %s not in clients anymore", s) # Deal with outgoing data: for s in wl: if s in self.clients: self.flushout(s) else: logging.error("Outgoing, but %s not in clients anymore", s) for s in xl: logging.error("EXCEPTION in %s. Closing", s) self.delClient(s)
def get_user_input(self): rlist, wlist, errlist = select([sys.stdin], [], [], 1) if rlist: user_input = sys.stdin.readline() return user_input else: return None
def play(client_socket): thread = Thread(target=write_input, args=[client_socket]) thread.start() buffer = '' while True: # check if we can read from server or write to it readable, _, _ = select([client_socket], [], []) if readable: data = client_socket.recv(1024) # EOF means server disconnected if not data: if buffer: print(colorize.colorize(buffer, colorize.Colors.server)) print( colorize.colorize('Disconnected from server', colorize.Colors.title)) break buffer += data.decode() if '\n' in buffer: print(colorize.colorize(buffer, colorize.Colors.server)) buffer = '' time.sleep(0.5) print(colorize.colorize('Press anything to continue', colorize.Colors.pink)) thread.join()
def start(host, port): global rand global has_winner srv = socket(AF_INET, SOCK_STREAM) srv.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) srv.bind((host, int(port))) srv.listen() sockets = [srv] while True: readable, _, _ = select(sockets, [], [], 1) if len(sockets) == 1: rand = random.randint(1, 100) has_winner = False print(f'New random {rand}') for active in readable: if active == srv: cli, addr = active.accept() print("New client connected ", addr) sockets.append(cli) else: msg = active.recv(1000) if not msg: active.close() sockets.remove(active) print("Client left") else: process_message(msg, active)
def wait_msg_from(self, timeout): endtime = time.time() + timeout msg = "" src_addr = None while time.time() < endtime: readset = select([self.sock], [], [], timeout) if len(readset) < 1 or not self.sock in readset[0]: if len(readset) < 1: print "select() returns " + str(len(readset)) elif not self.sock in readset[0]: print "select() alien socket" else: print "select other error" continue try: msg, src_addr = self.sock.recvfrom(2048) except: print "recv() exception: ", sys.exc_info()[0] continue if msg=="": return "", None if self.last_request=="INVITE" and self.rem_tag=="": self.rem_tag = get_tag(msg, "To") self.rem_tag = self.rem_tag.rstrip("\r\n;") if self.rem_tag != "": self.rem_tag = ";tag=" + self.rem_tag self.trace("=== rem_tag:" + self.rem_tag) self.trace("=========== RX MSG from " + str(src_addr) + " ===========\n" + msg) return (msg, src_addr)
def check(self, indi): # is the individual that was just evaluated the last in the generation? if int(indi) == model.get_max_indi_id_by_gen(model.get_cur_gen(int(indi))): # check if termination requirements are met if model.get_cur_gen(indi) >= model.get_max_num_gen(): # they are, end ga raise web.seeother('/terminate') else: # they are not, move onto selection select().select(int(indi)) # are there more to evaluate? elif int(indi) <= model.get_max_indi_id_by_gen(model.get_cur_gen(int(indi))): raise web.seeother('/fitness/' + str(int(indi) + 1)) # just in case exit condition else: raise web.seeother('/terminate')
def process_reactor(self): """ """ for ind in self.base: self.scale(ind) rsock, wsock, xsock = select(self.rsock, self.wsock, self.base, self.timeout) for ind in rsock: try: ind.drive(READ) except Root: pass for ind in wsock: try: ind.drive(WRITE) except Root: pass for ind in xsock: try: ind.drive(CLOSE) except Root: pass
def update(self): """ This method polls the sockets using select. It spawns either READ or WRITE. If one intents to use this reactor with some other reactor it might be called from other mainloop. """ # I dont need to define it here. r, w, x = [], [], [] r = filter(rmap, self.atom) w = filter(wmap, self.atom) resource = select(r , w , x, self.timeout) self.rsock, self.wsock, self.xsock = resource # This has to be in this order. # If a socket is in the list of WRITE event # it is expecting either to write or if it has connected. # If process_rsock is called first and the socket has connected # and the client has sent bytes you will not have your handle_connect # called first. self.process_wsock() self.process_rsock()
def iopoll(self, timeout): if self.read_waiting or self.write_waiting: r, w, e = select(self.read_waiting, self.write_waiting, [], timeout) for fd in r: self.schedule(self.read_waiting.pop[fd]) for fd in w: self.schedule(self.write_waiting.pop[fd])
def Start(self): # bind to the port, listen from everywhere self.udpservSocket.bind(('', self.port)) self.syslogSocket.bind(('', syslogport)) try: self.tcpservSocket.bind(('', self.port)) except: self.tcpservSocket.close() self.tcpservSocket.bind(('', self.port)) self.tcpservSocket.listen(3) second = time.time() counter = 0 self.connlist = [] selectList = [] self.connlist.append(self.tcpservSocket) self.connlist.append(self.udpservSocket) self.connlist.append(self.syslogSocket) self.permlist = [ self.tcpservSocket, self.udpservSocket, self.syslogSocket ] # self.permlist = [ self.tcpservSocket, self.udpservSocket ] #event loop while 1: parse = None results = select( self.connlist, [], []) #packets per second statistics if int(time.time()) != second: print "pps: %i" % counter counter = 0 second = int(time.time()) else: counter = counter + 1 #check for closing connections for con in results[0]: if self.permlist.count(con) == 0: print "closing connection" con.close() self.connlist.remove(con) #check for incoming connections if results[0].count(self.tcpservSocket) is not 0: print "incoming connection" consoc, conaddr = self.tcpservSocket.accept() print conaddr self.connlist.append(consoc) #incoming packets from syslog if results[0].count(self.udpservSocket) is not 0: data, addr = self.udpservSocket.recvfrom(self.bufsize) self.Parse(data, addr) if results[0].count(self.syslogSocket) is not 0: data, addr = self.syslogSocket.recvfrom(self.bufsize) self.Parse(data, addr)
def manageConn(wrcht1, wrcht2, wait = None): """ manageCommand() handles I/O with a child process wrcht1 and wrcht2 are wratchet objects which implement both sides of this communication. formerly: cmd == command to be executed fin == "stdin" equivalent for cmd. This will be read from fout == "stdout" equivalent for cmd. This will be written to """ try: tmp = None idle = 0 while (True): ### socket input handling ### if (wrcht1.select()): idle = 0 tmp = wrcht1.recv() if (len(tmp) == 0): break if (VERYVERBOSE): sys.stderr.write("sckt: len: %d\n%s"%(len(tmp),tmp)) wrcht2.send(tmp) ### command input handling ### if (wrcht2.select()): idle = 0 tmp = wrcht2.recv() if (VERYVERBOSE): sys.stderr.write("cmd: len: %d\n%s"%(len(tmp),tmp)) if (len(tmp) == 0): break wrcht1.send(tmp) idle += 1 if (wait and idle > (wait*10)): break select([],[],[], .1) except: print >>sys.stderr,("Score!!") try: sys.excepthook(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) wrcht1.close() wrcht2.close() except: pass sys.excepthook(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
def run(self): data = '' while False == self.__stop: infd,outfd,errfd=select([self.__sock], [], [], self.__timeout) if 0 != len(infd): data+=self.__sock.recv(self.recvOnce) infd,outfd,errfd=select([self.__sock], [], [], 0) while 0 != len(infd): #这里先把报文收全了 data+=self.__sock.recv(self.recvOnce) infd,outfd,errfd=select([self.__sock], [], [], 0) list, left = func_divPacket(data) data = left for packet in list: func_ParsePacket(packet) return
def expect(self, list, timeout=None): """Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of three items: the index in the list of the first regular expression that matches; the match object returned; and the text read up till and including the match. If EOF is read and no text was read, raise EOFError. Otherwise, when nothing matches, return (-1, None, text) where text is the text received so far (may be the empty string if a timeout happened). If a regular expression ends with a greedy match (e.g. '.*') or if more than one expression can match the same input, the results are undeterministic, and may depend on the I/O timing. """ re = None list = list[:] indices = range(len(list)) for i in indices: if not hasattr(list[i], "search"): if not re: import re list[i] = re.compile(list[i]) if timeout is not None: from time import time time_start = time() while 1: self.process_rawq() for i in indices: m = list[i].search(self.cookedq) if m: e = m.end() text = self.cookedq[:e] self.cookedq = self.cookedq[e:] return (i, m, text) if self.eof: break if timeout is not None: elapsed = time() - time_start if elapsed >= timeout: break s_args = ([self.fileno()], [], [], timeout - elapsed) r, w, x = select(*s_args) if not r: break self.fill_rawq() text = self.read_very_lazy() if not text and self.eof: raise EOFError return (-1, None, text)
def main_loop(): while True: read, write, error = select([server], [], [], 0) if len(read): client, address = server.accept() clients.append([client, address, []]) use = get_clients() try: read, write, error = select(use, [], [], 0) if len(read): for client in read: data = client.recv(1024) print(bytes.decode(data)) if data == 0: for c in clients: if c[0] == client: clients.remove(c) break else: for c in clients: c[2].append(data) except: print 'An error! Hurray!' try: use = get_clients() read, write, error = select([], use, [], 0) if len(write): for client in write: for c in clients: if c[0] == client: for data in c[2]: sent = client.send(data) if sent == len(data): c[2].remove(data) break except: print('An error! Hiphip!')
def run(self): """ yes, this was originally going to be multi-user, I don't feel like changing it now though. We shall loop. """ for conn in self.clist[:]: if conn.com.isOpen(): "pull data from serial and send it to tcp if possible" data = conn.recv_serial() if not data: pass else: conn.send_tcp(data) ready = self.clist[:] if self.listener: ready.append(self.listener) ready = select(ready, [], [], 0.1)[0] for conn in ready: if conn is self.listener: socket, address = self.listener.accept() global com try: com.close() com.open() except serial.SerialException: print "Error opening serial port. Is it in use?" sys.exit(1) conn = Connection(socket, com) self.clist.append(conn) "set up our initial telnet environment" conn.init_tcp() "we don't need to listen anymore" self.listener = None else: "pull some data from tcp and send it to serial, if possible." data = conn.recv_tcp() if not data: print "TCP connection closed." self.clist.remove(conn) self.start_new_listener() else: conn.send_serial(data)
def kbmonitor (): print 'kbmonitor started' while not terminated: try: (i,o,e)=select ([sys.stdin], [], [], 2) except Exception: lb.exit () if sys.stdin in i: c=sys.stdin.read(1) handle_key_press(c) print 'kbmonitor exited'
def doforwarding( self ): sockets = map( lambda x: x[1], self._proxysocks ) count = 0 size = 0 then = time.time() while 1: readylist, _, _ = select( sockets, [], [] ) for i in range(len(self._proxysocks)): port, sock = self._proxysocks[i] clientport = self._clientports[i] serverport = self._serverports[i] if sock in readylist: (packet, addr) = sock.recvfrom( 2048 ) # if addr == (self._serveraddr, serverport): if addr[0] == self._serveraddr: count = count + 1 size = size + len(packet) sock.sendto( packet, (self._clientaddr, clientport) ) now = time.time() elapsed = now - then if elapsed > 30.0: rate = (size * 8) / elapsed debug( "forwarding rate approx %dbps on ports %s" % (rate, self.getportrange()) ) count = 0 size = 0 then = now elif addr == (self._clientaddr, clientport): debug( "forwarding from client" ) sock.sendto( packet, (self._serveraddr, serverport) ) elif addr[0] == self._clientaddr: debug( "Change client port from %d to %d" % (clientport, addr[1]) ) self._clientports[i] = addr[1] # sock.sendto( packet, (self._serveraddr, serverport) ) sock.sendto( packet, (self._clientaddr, addr[1]) ) elif addr[1] == serverport: debug( "server %s lied about its' address, it's really %s" % ( self._serveraddr, addr[0]) ) self._serveraddr = addr[0] sock.sendto( packet, (self._clientaddr, clientport) ) else: debug( "forwarder received packet from unexpected source, %s:%d" % addr )