案例 多工版udp聊天器

2022-09-03 17:30:08 字數 1149 閱讀 1884

說明

要求
實現上述要求

總結多工程式的特點

參考**:
import socket

import threading

def send_msg(udp_socket):

"""獲取鍵盤資料,並將其傳送給對方"""

while true:

# 1. 從鍵盤輸入資料

msg = input("\n請輸入要傳送的資料:")

# 2. 輸入對方的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()

案例 多工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...

多工UDP聊天器

任務說明 import socket import threading 傳送資料函式 def send msg udp socket send content input 請輸入您要傳送的資料 send data send content.encode gbk dest port int input...