参数说明:
AF_INET:IPv4协议 AF_INET6: IPv6协议 SOCK_STREAM:面向流的TCP协议 SOCK_DGRAM: 面向无连接UDP协议
服务端
import socket server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(("127.0.0.1", 9998)) # 不需要调用listen()方法 # 接收来自任何客户端的数据 while True: data, addr = server.recvfrom(1024) print(data.decode("utf-8")) server.sendto(b"hello %s"% data.decode().encode(), addr)
客户端
import socket client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 不需要调用connect() client.sendto(b"hello", ("127.0.0.1", 9999)) print(client.recv(1024).decode("utf-8")) client.close()