多工UDP聊天器

2021-08-18 01:30:27 字數 1158 閱讀 8412

任務說明:

import  socket

import threading

# 傳送資料函式

def send_msg(udp_socket):

send_content = input("請輸入您要傳送的資料:")

send_data = send_content.encode("gbk")

dest_port = int(input("請輸入對方的埠號:"))

# 傳送資料

udp_socket.sendto(send_data, (dest_ip, dest_port))

# 接收資料函式

def recv_msg(udp_socket):

while true:

# 接收資料

recv_data, ip_port = udp_socket.recvfrom(1024)

# 解碼資料

recv_content = recv_data.decode("gbk")

print(recv_content, ip_port)

if __name__ == '__main__':

# 建立socket

udp_socket = socket.socket(socket.af_inet, socket.sock_dgram)

# 繫結埠

udp_socket.bind(("", 8080))

# 建立接收資料的執行緒

recv_thread = threading.thread(target=recv_msg, args=(udp_socket,))

# 守護主線程

recv_thread.setdaemon(true)

recv_thread.start()

while true:

option = input("請輸入功能選項1.傳送 2.退出:")

if option == '1':

send_msg(udp_socket)

elif option == '2':

break

# 關閉socket

udp_socket.close()

案例 多工udp聊天器

收和發不能同時進行 通過多執行緒來解決 import socket import threading def recv msg udp socket 接收資料並顯示 接收資料 while true recv data udp socket.recvfrom 1024 print recv data ...

多工版udp聊天器

import socket import threading def send msg udp socket 獲取鍵盤資料,並將其傳送給對方 while true 1.從鍵盤輸入資料 msg input n請輸入要傳送的資料 2.輸入對方的ip位址 3.輸入對方的port dest port int...

python 實現多工udp聊天器

相關 import socket import threading def recv msg udp socket 接收資料並顯示 接收資料 while true recv data udp socket.recvfrom 1024 print recv data def send msg udp ...