python高階(二)——多工(一)執行緒(2)多執行緒UDP聊天器
阿新 • • 發佈:2018-12-17
import socket import threading def recv_msg(udp_socket): # 接收資料 while True: recv_data = udp_socket.recvfrom(1024) print(recv_data) def send_msg(udp_socket, dest_ip, dest_port): # 傳送資料 while True: send_data = 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("", 7890) # 3 獲取對方ip dest_ip = input("ip:") dest_port = int(input("port:")) # 4 建立兩個執行緒 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()