聊天室服务器未关闭线程且在SIGINT时未退出

时间:2019-01-05 14:23:42

标签: python python-3.x server signals python-2.x

我在Python中有以下服务器程序,它可以模拟聊天室。该代码接受来自客户端的连接,并为每个客户端启动一个新线程。该线程将等待来自此客户端的消息。消息可以是L,以便服务器将以连接的客户端列表进行响应。ip:port msg,服务器将向客户端msg发送消息ip:port

在客户端,将有2个线程,一个用于接收来自服务器的消息,另一个用于发送。

import socket
from threading import Thread
#from SocketServer import ThreadingMixIn
import signal
import sys
import errno

EXIT = False
address = []
address2 = []

# handler per il comando Ctrl+C
def sig_handler(signum, frame):
    if (signum == 2):
        print("Called SIGINT")
        EXIT = True

signal.signal(signal.SIGINT, sig_handler) # setto l'handler per i segnali


# Multithreaded Python server : TCP Server Socket Thread Pool
class ClientThread(Thread):

    def __init__(self,conn,ip,port):
        Thread.__init__(self)
        self.conn = conn
        self.ip = ip
        self.port = port
        print ("[+] New server socket thread started for " + ip + ":" + str(port))
    def run(self):
        while True:
            data = self.conn.recv(1024)
            print ("Server received data:", data)
            if (data=='L'):
                #print "QUI",address2
                tosend = ""
                for i in address2:
                    tosend = tosend + "ip:"+str(i[0]) + "port:"+str(i[1])+"\n"
                self.conn.send(tosend)
                #mandare elenco client connessi
            else:
                #manda ip:port msg
                st = data.split(" ")
                msg = st[1:]
                msg = ' '.join(msg)
                print ("MSG 2 SEND: ",msg)
                ipport = st[0].split(":")
                ip = ipport[0]
                port = ipport[1]
                flag = False
                print ("Address2:",address2)
                print ("ip:",ip)
                print ("port:",port)
                for i in address2:
                    print (i[0],ip,type(i[0]),type(ip),i[1],type(i[1]),port,type(port))
                    if str(i[0])==str(ip) and str(i[1])==str(port):
                        i[2].send(msg)
                        self.conn.send("msg inviato")
                        flag = True
                        break
                if flag == False:
                    self.conn.send("client non esistente")


if __name__ == '__main__':
    # Multithreaded Python server : TCP Server Socket Program Stub
    TCP_IP = '127.0.0.1'
    TCP_PORT = 2004
    TCP_PORTB = 2005
    BUFFER_SIZE = 1024  # Usually 1024, but we need quick response

    tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    tcpServer.bind((TCP_IP, TCP_PORT))

    tcpServerB = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcpServerB.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    tcpServerB.bind((TCP_IP, TCP_PORTB))
    threads = []

    tcpServer.listen(4)
    tcpServerB.listen(4)

    while True:
        print("Multithreaded Python server : Waiting for connections from TCP clients...")
        try:
            (conn, (ip,port)) = tcpServer.accept()
        except socket.error as e: #(code, msg):
            if e.errno != errno.EINTR:
                raise
            else:
                break
        address.append((ip,port,conn))

        (conn2, (ip2,port2)) = tcpServerB.accept()
        address2.append((ip2,port2,conn2))

        newthread = ClientThread(conn,ip,port)
        newthread.start()
        threads.append(newthread)
        if EXIT==True:
            break

    print ("SERVER EXIT")

    for t in threads:
        t.join()

该代码具有用于SIGINT的信号处理程序,以使出口更整洁(关闭连接,向客户端发送消息(尚待实现),等等)。处理程序写入全局标志EXIT以使无限循环终止。

  1. 该代码可在Python2和Python3中运行。但是,CTRL-C生成的SIGINT信号存在一些问题。当没有客户端连接时,使用Python2启动的程序可以正确退出,而使用Python3的程序则无法退出。为什么这种行为上的差异?
  2. 考虑仅在Python2中运行程序,当客户端连接并按CTRL-C时,主线程退出,就像信号始终被主线程捕获一样,这会中断阻塞的系统调用accept。但是,我认为其他线程没有这样做,因为底层系统调用data = self.conn.recv(1024)被阻塞。在C语言中,我将阻塞一个线程的SIGINT信号,然后从另一个线程调用pthread_cancel。在Python中生成SIGINT时如何退出所有线程?

目前仅在Python2中运行并且遇到相同问题的客户端程序是:

# Python TCP Client A
import socket
from threading import Thread

class ClientThread(Thread):

    def __init__(self,conn):
        Thread.__init__(self)
        self.conn = conn

    def run(self):
        while True:
            data = self.conn.recv(1024)
            print "Ricevuto msg:",data

host = socket.gethostname()
print "host:",host
port = 2004
portB = 2005
BUFFER_SIZE = 2000

tcpClientA = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpClientB = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpClientA.connect(('127.0.0.1', port))
tcpClientB.connect(('127.0.0.1', portB))

newthread = ClientThread(tcpClientB)
newthread.start()


while(True):
    msg = raw_input("Inserisci comando: ")
    tcpClientA.send (msg)
    data = tcpClientA.recv(BUFFER_SIZE)
    print "data received:",data

tcpClientA.close()

1 个答案:

答案 0 :(得分:0)

对于Python 3中accept()的行为差异,请查看docs中的完整描述。我认为这是关键的声明:

  

版本3.5中的更改:如果系统调用被中断并且信号处理程序没有引发异常,则该方法现在重试系统调用,而不是引发InterruptedError异常(有关原理,请参阅PEP 475)。

另一个问题,在倒数第二句中指出:

  

在Python 2中生成SIGINT时如何从所有线程退出?

看看threading文档:

  

可以将一个线程标记为“守护程序线程”。该标志的重要性在于,仅保留守护程序线程时,整个Python程序都会退出。初始值是从创建线程继承的。可以通过daemon属性设置该标志。