这个模块允许你检查一个或多个socket接收数据,或者连接进来,同时也可以检查文件管道等等。
使用select函数可以检查多个socket是否可读、可写、出错等状态。
一个socket是否可读,主要有三种情况:1)新的连接进来 2)有数据可以接收 3)socket关闭、出错
输出结果如下:
五子棋游戏开发
http://edu.csdn.net/course/detail/5487
使用select函数可以检查多个socket是否可读、可写、出错等状态。
一个socket是否可读,主要有三种情况:1)新的连接进来 2)有数据可以接收 3)socket关闭、出错
一个socket是否可写,主要有两种情况:1)一个连接调用connect之后连接成功 2)数据可以发送
例子如下:
# File: select-example-1.py
import select
import socket
import struct, time
PORT = 8037
TIME1970 = 2208988800
service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
service.bind(("", PORT))
service.listen(1)
print("listening on port", PORT)
while True:
is_readable = [service]
is_writable = []
is_error = []
r, w, e = select.select(is_readable, is_writable, is_error, 1.0)
if r:
channel, info = service.accept()
print("connection from", info)
t = int(time.time()) + TIME1970
t = struct.pack("!I", t)
channel.send(t) # send timestamp channel.close() # disconnect
else:
print("still waiting")
输出结果如下:
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
connection from ('127.0.0.1', 53313)
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
still waiting
测试的客户端例子:
# File: socket-example-1.py
import socket
import struct, time
# server
HOST = '127.0.0.1'#"time.nist.gov"
PORT = 8037
# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800 # 1970-01-01 00:00:00
# connect to server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# read 4 bytes, and convert to time value
t = s.recv(4)
t = struct.unpack("!I", t)[0]
t = int(t - TIME1970)
s.close()
# print results
print("server time is", time.ctime(t))
print("local clock is", int(time.time()) - t, "seconds off")