服务端:
from socket import socket, AF_INET, SOCK_DGRAM recv_socket = socket(AF_INET, SOCK_DGRAM) recv_socket.bind(('127.0.0.1', 8888)) while True: data, addr = recv_socket.recvfrom(1024) # 接收数据 print('客户说:', data.decode('utf-8')) if data.decode('utf-8') == 'bye': break input_data = input('客服回:') recv_socket.sendto(input_data.encode('utf-8'), addr) if input_data == 'bye': break recv_socket.close()
客户端:
from socket import socket, AF_INET, SOCK_DGRAM send_socket = socket(AF_INET, SOCK_DGRAM) while True: data = input('客户说:') send_socket.sendto(data.encode('utf-8'), ('127.0.0.1', 8888)) if data == 'bye': break recv_data, addr = send_socket.recvfrom(1024) if recv_data.decode('utf-8') == 'bye': break print('客服回:', recv_data.decode('utf-8')) send_socket.close()
示例效果:
标签:DGRAM,UDP,utf,socket,示例,python,data,input,recv From: https://www.cnblogs.com/longfeiPHP/p/18375474