def timer(no, interval): cnt = 0 while cnt < 10: print('Thread:(%d) Time:%s\n' % (no, time.ctime())) time.sleep(interval) cnt += 1 _thread.exit_thread()
def child_connection(no, conn): print('begin connection', no) fp = None buffsize = 1024 txtpagesz = 1000 while True: try: rq = conn.recv(buffsize).decode('utf-8') print('request:', rq) if rq == '': break if rq[0] == '0': filename = rq[2:] print("the client is asking for a file", filename) filesize = os.path.getsize(filename) head_dic = {'filename': filename, 'filesize': filesize} head_raw = json.dumps(head_dic) head_len_struct = struct.pack('i', len(head_raw)) conn.sendall(head_len_struct) conn.sendall(head_raw.encode('utf-8')) with open(filename, 'rb') as fp: data = fp.read() conn.sendall(data) elif rq[0] == '1': filename = rq[2:] print('opening file..', filename) fpagenum = (os.path.getsize(filename) + txtpagesz - 1) // txtpagesz fp = open_text(filename) conn.sendall(str(fpagenum).encode('utf-8')) elif rq[0] == '2': pgnum = int(rq[2:]) if pgnum != 0: fp.seek((pgnum - 1) * txtpagesz) content = fp.read(txtpagesz) conn.sendall(content.encode('utf-8')) elif rq[0] == '3': print("closing file") fp.close() conn.sendall('file closed'.encode('utf-8')) else: conn.sendall('valid request'.encode('utf-8')) except Exception as e: conn.sendall(str(e).encode('utf-8')) print('end connection', no) conn.close() if fp: fp.close() thread.exit_thread()
def timer(no, interval): cnt = 0 while cnt < 5: print("Thread:(%d) Time:%s" % (no, time.ctime())) time.sleep(interval) cnt += 1 _thread.exit_thread()
def generation_handler(self): nr_of_generations = self.param_dict["Number of generations"] self.generator.callback(nr_of_generations) self.finish() _thread.exit_thread()
def child_connection(index, sock, connection): try: print("begin connecion ", index) print("begin connecion %d" % index) connection.settimeout(50) # 获得一个连接,然后开始循环处理这个连接发送的信息 while True: buf = connection.recv(1024) print("Get value %s from connection %d: " % (buf, index)) if buf == b'1': print("send welcome") connection.send('welcome to server!'.encode()) elif buf != b'0': connection.send('please go out!'.encode()) print("send refuse") else: print("close") break # 退出连接监听循环 except socket.timeout: # 如果建立连接后,该连接在设定的时间内无数据发来,则time out print('time out') print("closing connection %d" % index) # 当一个连接监听循环退出后,连接可以关掉 connection.close() # 关闭连接,最后别忘了退出线程 thread.exit_thread()
def child_connection(index, sock, connection): try: print("begin connecion ", index) print("begin connecion %d" % index) connection.settimeout(50) while True: buf = connection.recv(1024) print("Get value %s from connection %d: " % (buf, index)) if buf == b'1': print("send welcome") connection.send('welcome to server!'.encode()) elif buf != b'0': connection.send('please go out!'.encode()) print("send refuse") else: print("close") break except socket.timeout: print('time out') print("closing connection %d" % index) connection.close() thread.exit_thread()
def optimize(self): self.fetch_base_path() self.fetch_berkley_path() self.get_paths() trained_models_path = os.path.join(self.base_path, "model_data", "trained_models") if os.path.isdir(trained_models_path): shutil.rmtree(trained_models_path) os.mkdir(trained_models_path) # self.fetch_parameters() optimizer = ParetoOptimizer( template_path=self.template_path, output_path=self.output_path, bg_path=self.background_path, regularization_path=self.regularization_path, berkley_path=self.berkley_path, image_step=int(self.image_step), frame=self.drawing_canvas) result = run_optimization(optimizer, int(self.num_epochs)) costs, sol_vars = optimizer.decode_results(result) for i in range(0, len(costs)): print("Cost[{0}]={1}".format(i, costs[i])) print("Variables[{0}] = {1}".format(i, sol_vars[i])) _thread.exit_thread()
def adapter(searchListStr): searchList=searchListStr.split("#") #print("we get list:") #print(searchList) for key in searchList: search(key) _thread.exit_thread()
def ordering(interval): cnt = 0 while cnt < 100: print('好了,你订餐成功,订餐号码是:%d号 订餐时间是:%s 请在旁边耐心等待\n\n' % (cnt, time.ctime())) time.sleep(interval) cnt += 1 thread.exit_thread()
def notice(interval): cnt = 0 while cnt < 100: print('谁的号码是%d,您的餐好了,过来取一下\n' % cnt) time.sleep(interval) cnt += 1 thread.exit_thread()
def process_request(connection): r = connection.recv(1100) r = r.decode('utf-8') log('完整请求') log('请求结束') # log('ip and request, {}\n{}'.format(address, r)) # 因为 chrome 会发送空请求导致 split 得到空 list # 所以这里判断一下防止程序崩溃 if len(r.split()) < 2: connection.close() _thread.exit_thread() path = r.split()[1] # 创建一个新的 request 并设置 request = Request() request.method = r.split()[0] request.add_headers(r.split('\r\n\r\n', 1)[0].split('\r\n')[1:]) # 把 body 放入 request 中 request.body = r.split('\r\n\r\n', 1)[1] # 用 response_for_path 函数来得到 path 对应的响应内容 response = response_for_path(path, request) # 把响应发送给客户端 connection.sendall(response) print('完整响应') try: log('响应\n', response.decode('utf-8').replace('\r\n', '\n')) except Exception as e: log('异常', e) # 处理完请求, 关闭连接 connection.close() print('关闭')
def timer(no, interval): print("timer") cnt = 0 while cnt < 10: print('ThreadL(%d) Time:%s\n'%(no, time.time())) time.sleep(interval) cnt += 1 _thread.exit_thread()
def sms_4a(r, url, param, header, _proxies, _auth): r.post(url, data=param, headers=header, verify=False, proxies=_proxies, auth=_auth) _thread.exit_thread()
def video(s, dog): # establishes a udp connection with the server to # receive and display video. The video is just simulated for now name = '' # opens a UDP socket and sends its information over the open TCP # socket to the server try: name = list(dog.keys())[0] except AttributeError: print("Bad Human! You entered invalid input!") t.exit_thread() # create udp socket and sends its info to the server udp = socket(AF_INET, SOCK_DGRAM) c_ip = s.getsockname()[0] host = (c_ip, 0) udp.bind(host) c_port = udp.getsockname()[1] s.send(c_ip.encode()) s.send(str(c_port).encode()) # adds the port to the active ports list port_lock.acquire() open_ports.append(c_port) port_lock.release() # creates a separate window for streaming win = Tk() win.title(name) win.geometry('800x480') label = Label(win, text="Here's " + name + "!") label.place(x=350, y=200) # button didn't work (I'm guessing because of some concurrency issue) # button = Button(win, text="Quit", command=leave) # button.grid(row=1, column=3, padx=4) win.update() print("\nHit the 'x' button in the top right to exit stream") while True: try: # receives the frame from the server over the udp socket data, addr = udp.recvfrom(1024) data = data.decode() # print(data) # updates the tkinter window label["text"] = data win.update() except TclError: # removes this udp port from the active ports list # closes the udp socket and exits the thread port_lock.acquire() open_ports.remove(c_port) port_lock.release() del rooms[name] udp.close() t.exit_thread()
def do_receiving_messages(self): self.is_receiving_messages = True while self.is_receiving_messages: last_time = time() temp = self.send_request('NEXT') self.units, self.timestamp = temp self.timestamp -= self.server_time_delta sleep(max(PROCEED_DELAY - time() + last_time, 0)) _thread.exit_thread()
def do_sending_moves(self): self.is_sending_moves = True while self.is_sending_moves: last_time = time() if self.next_move is not None: point = self.next_move self.next_move = None self.send_request('MOVE', dx=point.x, dy=point.y, time=time()+self.server_time_delta) sleep(max(MOVE_DELAY - time() + last_time, 0)) _thread.exit_thread()
def Read(self): while(1): time.sleep(0.01); if(self.ReadStatus==2): self.readLock.acquire(); self.retStr=self.retStr+self.ReadCom(); self.readLock.release(); else: if(self.ReadStatus==0): break; _thread.exit_thread();
def add_num(name): global num while True: my_lock.acquire() print('Thread %s locked! num=%s' % (name, str(num))) if num >= 5: print('Thread %s released! num=%s' % (name, str(num))) my_lock.release() _thread.exit_thread() num += 1 print('Thread %s released ! num=%s' % (name, str(num))) time.sleep(2) my_lock.release()
def on_new_client(client_socket, addr): start_management_thread(current_connected_clients, _thread.get_ident()) while True: msg = client_socket.recv(1024) print(addr, ' >>', msg) print(current_connected_clients) try: msg = input("Server >>") client_socket.send(str.encode(msg + "\r\n")) except: client_socket.close() current_connected_clients.remove(_thread.get_ident()) print(current_connected_clients) _thread.exit_thread()
def startParsing(self, con, cliente): while True: data = con if not data: break if type(data) == bytes: data = data.decode("utf-8") # data = data.split() print("Dados Convertidos para UTF-8: ", data) #print("Dados que chegaram: ",data) try: dataCRC = data[-5::] dataNoCRC = data[:-5] dataNoCRC = dataNoCRC.rstrip(" ") print(dataNoCRC) crc = 0xFFFF # inicializa o crc except ValueError as e: print(e) print("Finalizando conexao do cliente", cliente) self.sock.sendto("CRC INVALIDO".encode('UTF-8'), ip) self.sock.close() _thread.exit() sys.exit(1) for ch in dataNoCRC: crc = calcByte(ch, crc) # falha do crc sai fora do parser if int(crc) != int(dataCRC): print("falaha do crc") print("crc calculado: " + str(crc)) print("CRC recebido: " + dataCRC) # nack = '\x15' nack = "Mensagem recebida! CRC Invalido" sock.sendto(nack.upper().encode('UTF-8'), cliente) self.sock.sendto(nack.upper().encode('UTF-8'), ip) # con.sendall(nack.upper().encode('UTF-8')) break sock.close() _thread.exit_thread() else: # print("crc deu certo") # ack = '\x06' ack = "Mensagem recebida! CRC VALIDO" self.sock.sendto(ack.upper().encode('UTF-8'), cliente) dadosParser = dataNoCRC.split() print(dadosParser) break
def Sender(sock, UserID): """ Fetch 'info' from queue send to UserID. """ Q = MsgQ[UserID] print("sender") try: while True: # get methord will be blocked if empty info = Q.get() sock.send(info.encode()) except Exception as e: print(e) sock.close() _thread.exit_thread()
def receiving(sckt): global Mutex global BASE global send_timer while True: pkt, addr = sckt.recvfrom(4096) if not pkt: break print("Control Packet was Received!") if not corrupted(pkt) and get_ack(pkt) >= BASE: Mutex.acquire() BASE = get_ack(pkt) + 1 send_timer.stop() Mutex.release() _thread.exit_thread()
def child_connection(index, sock, connection, address): try: print("begin connecion %d" % index) # 获得一个连接,然后开始循环处理这个连接发送的信息 while True: buf = connection.recv(1024).decode('utf-8') params = buf.split('||') req_handler(params, connection) except Exception: # 如果建立连接后,该连接在设定的时间内无数据发来,则time out print("closing connection %d" % index) # 当一个连接监听循环退出后,连接可以关掉 connection.close() if connection in conn_id: id = conn_id[connection][0] if id in id_conn: id_conn.pop(id) conn_id.pop(connection) # 关闭连接,最后别忘了退出线程 thread.exit_thread()
def checkThreadActive(threadList, mThread): """ :param threadList: 线程列表 :param mThread: 当前线程 :return:检查线程活跃情况,从线程列表中移除停止的线程,以及停止线程 """ start = time.clock() global control_flag while len(threadList) > 0 and time.clock()-start < waitingTime: for single in threadList: if single.thread_stop: threadList.remove(single) for single in threadList: single.stop() print("All Thread Over,Waiting,Success %d, Wrong %d" % (onceSuccess, onceSum-onceSuccess)) print("---------------------------") control_flag = 0 _thread.exit_thread()
def qhbCount(num): global lastCount global firstCount params = urllib.parse.urlencode({'ie': 'utf-8'}) headers = {'Accept':'application/json, text/javascript, */*; q=0.01','Content-Type':'application/x-www-form-urlencoded; charset=UTF-8','Host':'qhb.qbao.com','Origin':'http://qhb.qbao.com','User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36'} httpClient = http.client.HTTPConnection("qhb.qbao.com", timeout=30) httpClient.request("POST", "/ajax/refreshBuilding.html", params, headers) response = httpClient.getresponse() responseStr = response.read().decode('utf-8') strResponse = json.loads(responseStr) nowCount = strResponse["data"]["onlineUser"]["raffleCount"]+strResponse["data"]["onlineUser"]["groupRaffleCount"] if(firstCount==0): firstCount =nowCount if(lastCount ==0): lastCount =nowCount totalCount = firstCount - nowCount preCount = lastCount -nowCount lastCount = nowCount print('\n'+string1+str(nowCount)+string2+str(totalCount)+string3+str(preCount)) _thread.exit_thread()
def connectionAuthorise(soc, address): # Request format "LOGIN [USERNAME] [PASSWORD]" print("USER> Requesting a login") soc.send("DATA.REQUEST LOGIN".encode()) respond = soc.recv(1024).decode() print("USER> Package Received (" + respond + ")") username = respond.split(" ")[1] password = respond.split(" ")[2] print("USER> Logged in with " + username + " " + password) if users.password(username) == password: print("Logging in...") start_new_thread(connectionListener, (soc, address)) start_new_thread(connectionSender, (soc, address)) start_new_thread(connectionBrain, (soc, address)) print("Closing") exit_thread() print("test?")
def listen(): global s while True: try: s = socket.socket() s.connect((ip(), port())) while True: receive = pickle.loads(s.recv(1024)) print(receive) if receive == "close": s.close() showinfo('Close', 'Connection closed by Server!') else: print_received(receive) except Exception as e: print("error: %s" % e) if askyesno("Failed", "Connection failed! Do you want to retry?"): continue else: s.close() _thread.exit_thread()
def Receiver(sock): """ Receive 'msg' from UserID and store 'info' into queue. """ try: while True: info = sock.recv(1024).decode() print(info) info_unpack = info.split("|") receiver = info_unpack[1] exit_cmd = receiver == "SEVER" and info_unpack[3] == "EXIT" assert not exit_cmd, "{} exit".format(info_unpack[0]) if receiver not in MsgQ: MsgQ[receiver] = queue.Queue() MsgQ[receiver].put(info) except Exception as e: print(e) sock.close() _thread.exit_thread()
def serverHandler(clientSocket, fluff): global userNumber, ticTactToeBoard while True: prompt() #SELECT AND WAIT ON CLIENT SOCKET select.select([clientSocket], [], [], None) try: serverPacket = ParseServerMessage(clientSocket.recv(1024).decode()) except: _thread.exit_thread() #MEANING SERVER SENT AN OK MESSAGE if (serverPacket.status == 200): # print(serverPacket.message) if serverPacket.gameState == 1 or serverPacket.gameState == 2: if serverPacket.message == 'You are player 1': print(serverPacket.message) userNumber = 1 elif serverPacket.message == 'You are player 2': print(serverPacket.message) userNumber = 2 else: place = int(serverPacket.message) ticTactToeBoard[place - 1] = serverPacket.gameState displayBoard(ticTactToeBoard) elif serverPacket.gameState == 3: print(serverPacket.message) #RESET BOARD ON END OF GAME ticTactToeBoard = [0 for i in range(0, 9)] elif serverPacket.message is not None: displayMessage(serverPacket.message) #ELSE WAS 400 NOT OK MESSAGE else: if (serverPacket.message == 'Opponent disconnected'): print(serverPacket.message) displayMessage("I suppose you are the winner.") ticTactToeBoard = [0 for i in range(0, 9)] else: displayMessage(serverPacket.message)
def decrementer(self): while (self.decremented >= self.stopbid): time.sleep(10) itemlock.acquire() decrementAmount = int((self.starting - self.stopbid) / 5) self.decremented -= decrementAmount history_collection.insert_one({ "owner": self.owner, "title": self.title, "bidder": "decrementer", "bidAmount": decrementAmount, "isSold": False }) item = item_collection.find_one_and_update( { "owner": self.owner, "title": self.title }, {"$set": { "decremented": self.decremented }}) itemlock.release() if (self.newowner != ""): _thread.exit_thread()
def child_connection(index, server, conn): #参考助教PPT上关于多线程的代码 try: print("begin connection ", index) print("begin connection %d" % index) conn.settimeout(5000) #获得一个连接,然后开始循环处理这个连接发送的信息 while True: data = conn.recv(1024) #接收 if not data: print("Client is disconnected.") #客户端断开连接 break print("Received command:", data.decode("utf-8")) cmd = data.decode("utf-8").split(" ")[0] #get功能 if cmd == "get": file_name = data.decode("utf-8").split(" ")[1] file_dir = data.decode("utf-8").split(" ")[2] if os.path.isfile(file_name): # 判断文件存在 #显示发送文件的大小 head = os.stat(file_name).st_size #获取文件大小 conn.send(str(head).encode("utf-8")) # 发送数据长度 print("Head sent:", head) #发送文件内容 conn.recv(1024) #接收确认 m = hashlib.md5() file_sent = open(file_name, "rb") for line in file_sent: conn.send(line) #发送数据 m.update(line) file_sent.close() #根据md5值校验 md5 = m.hexdigest() conn.send(md5.encode("utf-8")) print("md5:", md5) else: head = -1 #如果服务器端没有响应的文件就返回头部-1 conn.send(str(head).encode("utf-8")) #put功能 if cmd == "put": file_dir = data.decode("utf-8").split(" ")[1] server_response = conn.recv(1024) file_size = int(server_response.decode("utf-8")) print("Head received:", file_size) #接收文件内容 conn.send("Ready to receive".encode("utf-8")) file_name = os.path.split(file_dir)[-1] file_received = open(file_name, "wb") actual_received_size = 0 m = hashlib.md5() while actual_received_size < file_size: size_single_time = 0 if file_size - actual_received_size > 1024: #分批接收 size_single_time = 1024 else: #最后一次接收 size_single_time = file_size - actual_received_size data = conn.recv(size_single_time) #多次接收内容,接收大数据 data_len = len(data) actual_received_size += data_len print("Already Received:", int(actual_received_size * 100 / file_size), "%") m.update(data) file_received.write(data) file_received.close() print("Actual size of received file:", actual_received_size) # 3.md5值校验 md5_sever = conn.recv(1024).decode("utf-8") md5_client = m.hexdigest() print("md5 of the server:", md5_sever) print("md5 of the client:", md5_client) if md5_sever == md5_client: print("Succeed to check md5.Pass!") else: print("Fail to check md5. Fail!") response = "100: Server successfully received.MD5 Check Pass!" #传送成功的时候会发送确认信息告诉客户端 conn.send(response.encode("utf-8")) # 发送数据长度 #查询服务器存放文件的目录 if cmd == "ask_dir": try: filename = data.decode("utf-8").split(" ")[1] except: filename = '' if len(filename) == 0: filedir = os.listdir() #如果缺省文件名,那么返回当前所在目录下的所有文件和文件名 else: filedir = GetFile(os.getcwd(), filename) conn.send(str(filedir).encode("utf-8")) except socket.timeout: # 如果建立连接后,该连接在设定的时间内无数据发来,则time out print('time out') print("closing connection %d" % index) # 当一个连接监听循环退出后,连接可以关掉 conn.close() # 关闭连接,最后别忘了退出线程 _thread.exit_thread()
def monitor(owenId): values = {'sEcho':1, 'iColumns':7, 'sColumns':',,,,,,', 'iDisplayStart':0, 'iDisplayLength':10, 'mDataProp_0':0, 'bRegex_0':'false', 'bSearchable_0':'true', 'mDataProp_1':1, 'bRegex_1':'false', 'bSearchable_1':'true', 'mDataProp_2':2, 'sSearch_2':'', 'bRegex_2':'false', 'bSearchable_2':'true', 'mDataProp_3':3, 'sSearch_3':'', 'bRegex_3':'false', 'bSearchable_3':'true', 'mDataProp_4':4, 'sSearch_4':'', 'bRegex_4':'false', 'bSearchable_4':'true', 'mDataProp_5':5, 'sSearch_5':'', 'bRegex_5':'false', 'bSearchable_5':'true', 'mDataProp_6':6, 'sSearch_6':'', 'bRegex_6':'false', 'bSearchable_6':'true', 'sSearch':'', 'bRegex':'false', 'ownerId':owenId, 'status':''} headers = {'Accept':'application/json, text/javascript, */*; q=0.01','Content-Type':'application/x-www-form-urlencoded; charset=UTF-8','Host':'qhb.qbao.com','Origin':'http://qhb.qbao.com','User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36'} data = urllib.parse.urlencode(values) httpClient = http.client.HTTPConnection("qhb.qbao.com", timeout=30) httpClient.request("POST", "/ajax/listGroup.html", data, headers) response = httpClient.getresponse() the_page =response.read().decode('utf-8') the_page_list = the_page.split("\r\n") the_page_now = "" if len(the_page_list)==1: the_page_now = the_page else: for i in range(len(the_page_list)): if(i%2 == 1): the_page_now=the_page_now+the_page_list[i] the_page_now = the_page_now.replace("\r\n","") strResponse = json.loads(the_page_now) aaData = strResponse["data"]["aaData"] small = 0; large = 0; for i in range(len(aaData)): if aaData[i]["status"] == "CLOSED": if aaData[i]["raffleCount"] >= 250: large += 1 elif aaData[i]["raffleCount"] < 250: small += 1 print('\n' + owenId+" "+"大团" + str(large) + "个---小团" + str(small) + "个") if "RAFFING" in str(aaData): lopper = False print('\n' + time.strftime( ISOTIMEFORMAT, time.localtime() )) print('\n' + owenId+ " " + ("大团" if aaData[i]["raffleCount"] > 250 else "小团") + " " +string) _thread.exit_thread()
output += str(single_data) + "," output += "\n" logfile.write(output) logfile.close() x_dropdown.currentIndexChanged.connect(change_x_axis) y_dropdown.currentIndexChanged.connect(change_y_axis) transform_dropdown.currentIndexChanged.connect(change_transform) center_tag_input.textEdited.connect(change_center_tag) data_point_spin.sigValueChanged.connect(change_data_length) outer_tag_input.textEdited.connect(change_outer_tag) origin_input.textEdited.connect(change_origin) pause_button.clicked.connect(pause_handler) clear_data_button.clicked.connect(clear_data_handler) lan_data_checkbox.clicked.connect(lan_data_handler) color_dropdown.currentIndexChanged.connect(color_handler) export_button.clicked.connect(export_handler) timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(40) if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): app.exec_() data_handler.consumer.cleanup() app.closeAllWindows() _thread.exit_thread()
def delay(): global Trial time.sleep(Delay) Trial = 0 _thread.exit_thread()
def thread_end(sock_client, con_id): sock_client.close() con_index.remove(con_id) print("%sZakończono obsługę tego połączenia." % get_date_time(con_id)) thread.exit_thread()
__author__ = 'Hernan Y.Ke' import time import _thread def foo(t): print(time.time()) time.sleep(t) print("done") print(time.time()) _thread.start_new_thread(foo,(3,)) _thread.exit_thread()
def progress(self, percent, message=''): if self._cancel[0]: exit_thread() i = self._stage - 1 p = ((sum(self._STAGES[:i]) + percent*self._STAGES[i]) / float(sum(self._STAGES))) self._progress[0] = p