我正在创建一个可以侦听多个端口(在portslist中定义)的python脚本,当有人连接到这些端口时,就会出现一个"你好"消息将发送给他们。目前,下面的代码为端口列表中的所有端口创建套接字,但仅在最后一个端口上向通信发送消息。
由于
servers = []
for port in portlist:
datasocket = ("0.0.0.0", port)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(datasocket)
server.listen(5)
servers.append(server)
while True:
ready_server = select.select(servers, [], [])
for s in ready_server:
connection, address = server.accept()
print str(address) + " has connected!\n"
msg ="hello\n"
connection.send(msg)
connection.close()
答案 0 :(得分:1)
当select.select
返回时,ready_server
将是这样的列表列表:
[[<sockets ready to read from>], [], []]
所以for s in ready_server
会迭代这些列表,而不是套接字。
此外,该循环中的server.accept()
并不引用任何循环变量,而是引用前一循环中的server
。
试试这个:
servers = []
for port in portlist:
datasocket = ("0.0.0.0", port)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(datasocket)
server.listen(5)
servers.append(server)
while True:
# unpack the returned list
ready_server, _, _ = select.select(servers, [], [])
for s in ready_server:
# use s.accept instead of server.accept
connection, address = s.accept()
print str(address) + " has connected!\n"
msg ="hello\n"
connection.send(msg)
connection.close()