本文實例講述了python實現的多任務版udp聊天器。分享給大家供大家參考,具體如下:
說明
編寫一個有2個線程的程序
線程1用來接收數據然后顯示
線程2用來檢測鍵盤數據然后通過udp發送數據
要求
實現上述要求
總結多任務程序的特點
參考代碼:
import socketimport threadingdef send_msg(udp_socket): """獲取鍵盤數據,并將其發送給對方""" while True: # 1. 從鍵盤輸入數據 msg = input("/n請輸入要發送的數據:") # 2. 輸入對方的ip地址 dest_ip = input("/n請輸入對方的ip地址:") # 3. 輸入對方的port dest_port = int(input("/n請輸入對方的port:")) # 4. 發送數據 udp_socket.sendto(msg.encode("utf-8"), (dest_ip, dest_port))def recv_msg(udp_socket): """接收數據并顯示""" while True: # 1. 接收數據 recv_msg = udp_socket.recvfrom(1024) # 2. 解碼 recv_ip = recv_msg[1] recv_msg = recv_msg[0].decode("utf-8") # 3. 顯示接收到的數據 print(">>>%s:%s" % (str(recv_ip), recv_msg))def main(): # 1. 創建套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 2. 綁定本地信息 udp_socket.bind(("", 7890)) # 3. 創建一個子線程用來接收數據 t = threading.Thread(target=recv_msg, args=(udp_socket,)) t.start() # 4. 讓主線程用來檢測鍵盤數據并且發送 send_msg(udp_socket)if __name__ == "__main__": main()
更多關于Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答