gpt4 book ai didi

Python 套接字只允许一个连接,但在新连接时断开连接,而不是拒绝

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:00 25 4
gpt4 key购买 nike

在python中,你可以通过listen()函数的参数来定义最大socket连接数...例如:

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

最佳答案

我不确定我是否完全理解你的问题,但我认为下面的例子可以满足你的要求。服务器可以断开旧用户并为新用户提供服务。

服务器端:

#!/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)

试一试:-)

关于Python 套接字只允许一个连接,但在新连接时断开连接,而不是拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31742705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com