所任務udp聊天器

2021-09-26 20:14:30 字數 1229 閱讀 7740

#--coding=utf8--

import socket

import threading

# 雙工socket,每個端2個執行緒,乙個收乙個發

# 接收資訊

def recv_msg(udp_socket):

while true:

rec_data= udp_socket.recvfrom(1024)

print(rec_data)

# 傳送資料

def send_msg(udp_socket, dest_ip, dest_port):

while true:

send_data = raw_input("請輸入要傳送的資料:")

udp_socket.sendto(send_data.encode("utf-8"), (dest_ip, dest_port))

def main():

''' 完成udp聊天器的整體控制 '''

# 1.建立套接字

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

# 2.繫結本地資訊

udp_socket.bind(("", 7788))

# 3.獲取對方的ip

dest_ip = raw_input("請輸入對方的ip:")

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

# 建立兩個執行緒,分別去傳送和接收資料

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

t_send = threading.thread(target=send_msg, args = (udp_socket, dest_ip, dest_port))

# 啟動執行緒

t_recv.start()

t_send.start()

if __name__ == "__main__":

main()

netassist.exe作為對方:

本地虛擬機器:

多工UDP聊天器

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

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