Maison  >  Questions et réponses  >  le corps du texte

如何终止用python写的socket服务端程序?

用python写了一个socket服务端的程序,但是启动之后由于监听连接的是一个死循环,所以不知道怎样在cmd运行程序的时候将其终止。

#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import threading, time

def tcplink(sock,addr):
    print('Accept new connection from %s:%s...' %addr)
    sock.send(b'Welcome!')
    while True:
        data=sock.recv(1024)
        time.sleep(1)
        if not data or data.decode('utf-8')=='exit':
            break
        sock.send(('Hello,%s!'% data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print('Connection from %s:%s closed.' % addr)
    
s=socket.socket()
s.bind(('127.0.0.1',1234))
s.listen(5)
print('Waiting for conection...')

while True:
    #accept a new connection
    sock,addr=s.accept()
    #create a new thread
    t=threading.Thread(target=tcplink,args=(sock,addr))
    t.start()

在win10上的cmd运行后的情况是按ctrl+c,ctrl+z,ctrl+d都不能终止,请问要怎么终止程序?

黄舟黄舟2740 Il y a quelques jours746

répondre à tous(6)je répondrai

  • 迷茫

    迷茫2017-04-18 10:22:24

    Ctrl + C

    répondre
    0
  • PHPz

    PHPz2017-04-18 10:22:24

    在启动线程之前,添加 setDaemon(True)

    while True:
        #accept a new connection
        sock,addr=s.accept()
        #create a new thread
        t=threading.Thread(target=tcplink,args=(sock,addr))
        t.setDaemon(True)  # <-- add this
        t.start()
        
    

    démon

    Une valeur booléenne indiquant si ce thread est un démon
    thread (True) ou non (False). Ceci doit être défini avant que start() soit
    appelé, sinon RuntimeError est déclenché. Sa valeur initiale est
    héritée du thread créateur ; le thread principal n'est pas un démon
    thread et donc tous les threads créés dans le thread principal sont par défaut
    daemon = False.

    L'ensemble du programme Python se termine lorsqu'il ne reste plus aucun thread non-démon actif
    .

    这样 <C-c> 的中断信号就会被 rasie。

    répondre
    0
  • 阿神

    阿神2017-04-18 10:22:24

    kill -9

    répondre
    0
  • 高洛峰

    高洛峰2017-04-18 10:22:24

    Fermez la fenêtre de commande cmd et rouvrez une cmd, c'est ce que j'ai fait.

    répondre
    0
  • ringa_lee

    ringa_lee2017-04-18 10:22:24

    Vous pouvez utiliser le module de signal. Lorsque vous appuyez sur Ctrl+C, capturez les informations puis quittez.

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import signal
    
    def do_exit(signum, frame):
        print("exit ...")
        exit()
    
    signal.signal(signal.SIGINT, do_exit)
    
    while True:
        print("processing ...")
    

    répondre
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:22:24

    Je me souviens que je peux

    try:
        ......
    except KeyboardInterrupt:
        exit()

    répondre
    0
  • Annulerrépondre