TCP与UDP区别以及UDP的python示例
服务器端python示例:
import socket server_ip = '127.0.0.1' server_port = 9999 # 建立套接字 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket.SOCK_DGRAM代表是UDP通信 # 绑定IP和端口 s.bind((server_ip, server_port)) print('Bind UDP Server on %s:%s' % (server_ip, server_port)) while True: # 接收数据 data, addr = s.recvfrom(1024) print(addr, "\t", data) # 发送数据 s.sendto(b'Received:%s'%data, addr)
客户端python代码示例:
import socket server_ip = '127.0.0.1' server_port = 59955 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket.SOCK_DGRAM代表是UDP通信 for data in [b'Michael', b'Tracy', b'Sarah']: # 发送数据 s.sendto(data, (server_ip, server_port)) # 接收数据 # print(s.recv(1024).decode('utf-8')) s.close()