例子来自于Python文档18.1.5
服务器程序,在客户端发过来的消息前加上当前的时间戳,并发送回客户端。
from socket import *
from time import ctime
import sys
HOST = None # Symbolic name meaning all available interfaces
PORT = 21560
BUFSIZ = 1024
s = None
# 根据给定的参数host/port,相应的转换成一个包含用于创建socket对象的五元组
# AF_UNSPEC: IPv4 IPv6
for res in getaddrinfo(HOST, PORT, AF_UNSPEC,
SOCK_STREAM, 0, AI_PASSIVE):
# print(res)
af, socktype, proto, canonname, sockaddr = res
try:
s = socket(af, socktype, proto) # create a socket object
except OSError as msg:
s = None
continue
try:
s.bind(sockaddr)
s.listen(5)
except OSError as msg:
s.close()
s = None
continue
break
if s is None:
print('cound not open socket')
sys.exit(1)
while True:
print('waiting for connection...')
client, addr = s.accept()
with client:
try