哪里是关闭服务器套接字的正确位置(Python)
我有一个服务器程序,可以维护与多个客户端的连接。我希望能够关闭套接字以响应close by close by client消息,或者出于其他原因。问题是,服务器卡在accept()方法上,不关心是否在其他位置关闭套接字 我可以在主服务器中使用一些标志,然后在这段时间后关闭套接字,但是这意味着我必须在客户端请求后自己连接到服务器,以便检查while条件,这听起来像是非常糟糕的编程 守则:哪里是关闭服务器套接字的正确位置(Python),python,sockets,Python,Sockets,我有一个服务器程序,可以维护与多个客户端的连接。我希望能够关闭套接字以响应close by close by client消息,或者出于其他原因。问题是,服务器卡在accept()方法上,不关心是否在其他位置关闭套接字 我可以在主服务器中使用一些标志,然后在这段时间后关闭套接字,但是这意味着我必须在客户端请求后自己连接到服务器,以便检查while条件,这听起来像是非常糟糕的编程 守则: import socket import sys from thread import * HOST = '
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 9992 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\r\n') #send only takes string
data=''
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data += conn.recv(1024)
print data
if data == 'CLOSE':
global s
conn.sendall('You have requested to destroy the connection...')
conn.close()
s.close()
return
if data.find('\n') != -1:
conn.sendall('OK...' + data + '\r\n')
data=''
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
try:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
except:
print 'socket issue sorry'
break
您的问题不清楚,您的评论也不清楚:)当客户端发送“关闭”消息时,您希望服务器仅断开该客户端还是关闭整个服务器,即断开所有客户端并退出?我希望断开所有客户端,而不是等待更多传入连接。我想离开这里,等等。