由于某些原因,我无法将选择套接字与我的套接字字典相匹配。下面的代码创建了一个套接字字典(确实如此)然后当有人连接接受时(它不接受)。它在'L'中找到's',但不能socket.error: [Errno 22] Invalid argument
listening = {}
L = []
for link in links:
try:
# listening
listening[link] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listening[link].bind((host, routers[routername].baseport+links[link].locallink))
listening[link].listen(backlog)
# append routes and listen-list
L.append(listening[link])
except socket.error, (value,message):
print "Could not open socket: " + message
sys.exit(1)
# run loop
input = L
running = 1
while running:
inputready,outputready,exceptready = select.select(input,[],[], 0)
# Sockets loop
for s in inputready:
if s in L:
# handle the server socket
client, address = s.accept()
input.append(client)
答案 0 :(得分:0)
我认为问题是当你将append客户端套接字添加到(输入)时,你也将它添加到(L)。这是因为输入和L都指向同一个列表对象。然后,当新连接的客户端套接字向您发送一些数据时,您尝试在客户端套接字上调用accept(),但当然客户端套接字不是监听套接字,因此您会收到您看到的错误。
作为input.append(客户端)将客户端添加到L的原因的示例,这里是我的Python解释器的片段:
Jeremys-Mac-mini:python lcsuser1$ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> L = [1,2,3]
>>> print L
[1, 2, 3]
>>> input = L
>>> print input
[1, 2, 3]
>>> input.append(4)
>>> print input
[1, 2, 3, 4]
>>> print L
[1, 2, 3, 4] <-- d'oh!
要修复,请替换
行input = L
与
input = list(L)
因此输入指向L的副本,而不是指向L本身。
答案 1 :(得分:0)
虽然我在第一次尝试时不确定所有的错误,但我已经解决了自己的困境。 @Jeremy在正确的轨道上,但稍微偏离(可能是由于我的描述)。套接字不会在s
之外引用,因此不需要是字典。但是,select只取一个列表而不是使其他数据类型复杂化,坚持使用列表并引用s
而不是L
(s
是你想要的东西)
L = []
input = [sys.stdin]
for i in range(4):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host,port+i))
server.listen(backlog)
L.append(server)
input.append(server)
running = 1
print len(L)
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for s in inputready:
if s in L:
# handle the server socket
print "opened"
client, address = s.accept()
input.append(client)
elif s == sys.stdin:
# handle standard input
junk = sys.stdin.readline()
running = 0
else:
# handle all other sockets
data = s.recv(size)