我有一个python脚本来接收netcat发送的字符串。它有效,当我有1个客户端发送字符串,但第二个无法连接。
import socket
HOST = 'localhost' # use '' to expose to all networks
PORT = 12345
def incoming(host, port):
"""Open specified port and return file-like object"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# set SOL_SOCKET.SO_REUSEADDR=1 to reuse the socket if
# needed later without waiting for timeout (after it is
# closed, for example)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(0) # do not queue connections
request, addr = sock.accept()
return request.makefile('r', 0)
# /-- network ---
for line in incoming(HOST, PORT):
print line,
我将来自2个客户端的字符串发送到此脚本,但是当第二个客户端开始发送时,连接被中断。 是否可以允许多于1个同时连接?
将sock.listen()更改为更大的数字无效
答案 0 :(得分:1)
您只接受一个连接。此外,我觉得很奇怪你想要复制文件描述符并像现在一样阅读它。所以,为什么不尝试这样的事情:产生传入的请求并在超时时抛出StopIteration,作为奖励,使用recv代替
import socket
HOST = 'localhost' # use '' to expose to all networks
PORT = 12345
def incoming(host, port):
"""Open specified port and yield requests"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(10)
sock.bind((host, port))
sock.listen(0)
try:
while True:
request, addr = sock.accept()
yield request
request.close()
except socket.timeout:
raise StopIteration
finally:
sock.close()
for request in incoming(HOST, PORT):
print request.recv(1024)