本文實(shí)例為大家分享了Python實(shí)現(xiàn)多任務(wù)版的udp聊天器,供大家參考,具體內(nèi)容如下
1、編寫一個(gè)有2個(gè)線程的程序。
2、線程1用來接收數(shù)據(jù)然后顯示。
3、線程2用來檢測鍵盤數(shù)據(jù)然后通過udp發(fā)送數(shù)據(jù)。
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)建一個(gè)子線程用來接收數(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()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
標(biāo)簽:雅安 辛集 渭南 濰坊 七臺河 西安 贛州 許昌
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python實(shí)現(xiàn)多任務(wù)版的udp聊天器》,本文關(guān)鍵詞 Python,實(shí)現(xiàn),多任務(wù),版,的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。