新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
如何使用Python實(shí)現(xiàn)多任務(wù)版的udp聊天器
本篇文章將為大家分享一下如何使用Python實(shí)現(xiàn)多任務(wù)版的udp聊天器,結(jié)合具體案例形式分析了Python基于udp的聊天器功能相關(guān)實(shí)現(xiàn)與使用技巧,有需要的小伙伴可以參考一下。

成都創(chuàng)新互聯(lián)專注于成都網(wǎng)站制作、成都做網(wǎng)站、外貿(mào)營銷網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計、網(wǎng)站制作、網(wǎng)站開發(fā)。公司秉持“客戶至上,用心服務(wù)”的宗旨,從客戶的利益和觀點(diǎn)出發(fā),讓客戶在網(wǎng)絡(luò)營銷中找到自己的駐足之地。尊重和關(guān)懷每一位客戶,用嚴(yán)謹(jǐn)?shù)膽B(tài)度對待客戶,用專業(yè)的服務(wù)創(chuàng)造價值,成為客戶值得信賴的朋友,為客戶解除后顧之憂。
一、案例示例
二、案例說明
1、編寫一個有2個線程的程序。
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)建一個子線程用來接收數(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()
當(dāng)前題目:如何使用Python實(shí)現(xiàn)多任務(wù)版的udp聊天器
本文鏈接:http://www.5511xx.com/article/dpccjdd.html


咨詢
建站咨詢
