Python 實現udp簡單通訊
學習網址指路:https://www.cnblogs.com/greatfish/p/7368433.html
server端:
import socket port=12345 host='' addr=(host,port) server_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) server_socket.bind(addr) while True: receive_data,client_address=server_socket.recvfrom(1024) print("客戶端",client_address,":",receive_data.decode()) send_data=input("請輸入資訊:") if not send_data: break server_socket.sendto(send_data.encode(),client_address) server_socket.close()
client端:
import socket host='localhost' port=12345 address=(host,port) client_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: msg=input("請輸入要傳送的內容:") if not msg: break client_socket.sendto(msg.encode(),address) receive_data,sender_address=client_socket.recvfrom(1024) print("來自伺服器端",sender_address,":",receive_data.decode())