首先写好服务器,在本程序里的端口指的是自身服务器上的端口号,用于区分同在一个服务器上的其他程序。客户端正是凭借着这个端口号和服务器的ip地址来找到服务器,并对之提出请求。
#!/usr/bin/env python
# UDP Wrong Time Server - Chapter 3 - udptimeserver.py
import socket, traceback, time, struct
host = '' # Bind to all interfaces
port = 51423
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
print "Waiting for connections..."
while 1:
try:
message, address = s.recvfrom(8192)
secs = int(time.time()) # Seconds since 1/1/1970
secs -= 60 * 60 * 24 # Make it yesterday
secs += 2208988800 # Convert to secs since 1/1/1900
reply = struct.pack("!I", secs)
s.sendto(reply, address)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
接下来是写好客户端~ 可以看到程序中没有用到connect,而是用了sendto还有recvfrom
#!/usr/bin/env python
# UDP Connectionless Example - Chapter 2 - udptime.py
import socket, sys, struct, time
hostname = '127.0.0.1'
port = 51423
host = socket.gethostbyname(hostname)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto('', (host, port))
print "Looking for replies; press Ctrl-C to stop."
buf = s.recvfrom(2048)[0]
if len(buf) != 4:
print "Wrong-sized reply %d: %s" % (len(buf), buf)
sys.exit(1)
secs = struct.unpack("!I", buf)[0]
secs -= 2208988800
print time.ctime(int(secs))