在python中,您可以通过listen()
函数的参数定义最大套接字连接数...例如:
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), 80))
serversocket.listen(1) // allow only 1 connection
但问题是当第二个客户想连接时,连接被拒绝。我想断开旧用户并连接新用户。有人可以帮我吗?
可能是答案:
我发帖是因为它很可能是答案(我没时间检查)
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), 80))
serversocket.listen(10) // allow 10 connections, but disconnect previous later
someone_connected = 0
while 1:
(clientsocket, address) = serversocket.accept()
if(someone_connected) someone_connected.close()
someone_connected = clientsocket
答案 0 :(得分:3)
我不确定我是否完全理解您的问题,但我认为以下示例可以满足您的要求。服务器可以断开旧用户的连接并为新用户提供服务。
服务器端:
#!/usr/bin/env python
import socket
import multiprocessing
HOST = '127.0.0.1'
PORT = 50007
# you can do your real staff in handler
def handler(conn, addr):
try:
print 'processing...'
while 1:
data = conn.recv(1024)
if not data:
break
print data
conn.sendall(data)
conn.close()
print 'processing done'
except:
pass
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(5)
processes = []
while True:
conn, addr = s.accept()
print conn, addr
[p.terminate() for p in processes] # to disconnect the old connection
# start process newer connection and save it for next kill
p = multiprocessing.Process(target=handler, args=(conn, addr))
processes = [p]
p.start()
newest_conn = conn # this is the newest connection object, if you need it
对于测试,客户端:
#!/usr/bin/env python
import socket
import time
import multiprocessing
HOST = '127.0.0.1'
PORT = 50007
def client():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
time.sleep(0.1)
try:
for n in range(20):
s.send(str(n))
data = s.recv(1024)
print data
time.sleep(0.5)
s.send('')
s.close()
except:
pass
if __name__ == "__main__":
for i in range(5):
print 'user %i connect' %i
p = multiprocessing.Process(target=client)
p.start() # simulate a new user start connect
time.sleep(3)
试一试: - )
答案 1 :(得分:1)
您的问题内置了错误的假设 - 套接字listen()
的单个参数不是"连接数",而是 backlog
- 内核暂时为您保留的待处理但尚未接受的客户端连接数。
您的问题似乎是您已经接受了一个连接,并在循环中读取/写入它,而不是再次调用accept()
。内核保留对某些超时的任何新客户端连接的请求,然后通知客户端服务器不接受它。
您希望按照评论中的建议查看select()
功能。