1. 程式人生 > 程式設計 >python實現的多工版udp聊天器功能案例

python實現的多工版udp聊天器功能案例

本文例項講述了python實現的多工版udp聊天器。分享給大家供大家參考,具體如下:

說明

編寫一個有2個執行緒的程式
執行緒1用來接收資料然後顯示
執行緒2用來檢測鍵盤資料然後通過udp傳送資料

要求

實現上述要求
總結多工程式的特點

參考程式碼:

import socket
import threading
def 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程式設計有所幫助。