您好,登錄后才能下訂單哦!
小編給大家分享一下python如何實現(xiàn)多任務(wù)版udp聊天器功能,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
python實現(xiàn)的多任務(wù)版udp聊天器,具體如下:
說明
編寫一個有2個線程的程序
線程1用來接收數(shù)據(jù)然后顯示
線程2用來檢測鍵盤數(shù)據(jù)然后通過udp發(fā)送數(shù)據(jù)
要求
實現(xiàn)上述要求
總結(jié)多任務(wù)程序的特點
參考代碼:
import socket import threading def send_msg(udp_socket): """獲取鍵盤數(shù)據(jù),并將其發(fā)送給對方""" while True: # 1. 從鍵盤輸入數(shù)據(jù) msg = input("\n請輸入要發(fā)送的數(shù)據(jù):") # 2. 輸入對方的ip地址 dest_ip = input("\n請輸入對方的ip地址:") # 3. 輸入對方的port dest_port = int(input("\n請輸入對方的port:")) # 4. 發(fā)送數(shù)據(jù) udp_socket.sendto(msg.encode("utf-8"), (dest_ip, dest_port)) def recv_msg(udp_socket): """接收數(shù)據(jù)并顯示""" while True: # 1. 接收數(shù)據(jù) recv_msg = udp_socket.recvfrom(1024) # 2. 解碼 recv_ip = recv_msg[1] recv_msg = recv_msg[0].decode("utf-8") # 3. 顯示接收到的數(shù)據(jù) print(">>>%s:%s" % (str(recv_ip), recv_msg)) def main(): # 1. 創(chuàng)建套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 2. 綁定本地信息 udp_socket.bind(("", 7890)) # 3. 創(chuàng)建一個子線程用來接收數(shù)據(jù) t = threading.Thread(target=recv_msg, args=(udp_socket,)) t.start() # 4. 讓主線程用來檢測鍵盤數(shù)據(jù)并且發(fā)送 send_msg(udp_socket) if __name__ == "__main__": main()
以上是“python如何實現(xiàn)多任務(wù)版udp聊天器功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。