调用bind函数绑定一个端口,然后接收到客户端数据再发送回去:
# File: socket-example-5.py
import socket
import struct, time
# user-accessible port
PORT = 8037
# reference time
TIME1970 = 2208988800
# establish server
service = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
service.bind(("", PORT))
print("listening on port", PORT)
while 1:
# serve forever
data, client = service.recvfrom(0)
print("connection from", client)
t = int(time.time()) + TIME1970
t = struct.pack("!I", t)
service.sendto(t, client) # send timestamp
输出结果如下:
======= RESTART: D:/work/****/python_Game1/example/socket-example-5.py =======
listening on port 8037
connection from ('127.0.0.1', 59979)
connection from ('127.0.0.1', 59980)
connection from ('127.0.0.1', 59981)
在这里主要调用recvfrom接收数据,要注意接收0个字节。下面就是来测试UDP的客户端:
# File: socket-example-4.pyimport socketimport struct, time# serverHOST = "127.0.0.1"PORT = 8037# reference time (in seconds since 1900-01-01 00:00:00)TIME1970 = 2208988800 # 1970-01-01 00:00:00# connect to servers = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)# send empty packets.sendto(''.encode(), (HOST, PORT))# read 4 bytes from server, and convert to time valuet, server = s.recvfrom(4)t = struct.unpack("!I", t)[0]t = int(t - TIME1970)s.close()print("server time is", time.ctime(t))print("local clock is", int(time.time()) - t, "seconds off")