如何終止用python寫的socket服務(wù)端程序?
問(wèn)題描述
用python寫了一個(gè)socket服務(wù)端的程序,但是啟動(dòng)之后由于監(jiān)聽連接的是一個(gè)死循環(huán),所以不知道怎樣在cmd運(yùn)行程序的時(shí)候?qū)⑵浣K止。
#!/usr/bin/python# -*- coding: utf-8 -*-import socketimport threading, timedef 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’: breaksock.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運(yùn)行后的情況是按ctrl+c,ctrl+z,ctrl+d都不能終止,請(qǐng)問(wèn)要怎么終止程序?
問(wèn)題解答
回答1:Ctrl + C
回答2:在啟動(dòng)線程之前,添加 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()
daemon
A boolean value indicating whether this thread is a daemonthread (True) or not (False). This must be set before start() iscalled, otherwise RuntimeError is raised. Its initial value isinherited from the creating thread; the main thread is not a daemonthread and therefore all threads created in the main thread default todaemon = False.
The entire Python program exits when no alive non-daemon threads areleft.
這樣 <C-c> 的中斷信號(hào)就會(huì)被 rasie。
回答3:kill -9回答4:
關(guān)閉cmd命令窗口,重新開啟一個(gè)cmd,我是這么做的。
回答5:可以使用signal模塊,當(dāng)按住Ctrl+C時(shí),捕捉信息,然后退出.
#!/usr/bin/env python# -*- coding: utf-8 -*-import signaldef do_exit(signum, frame): print('exit ...') exit()signal.signal(signal.SIGINT, do_exit)while True: print('processing ...')回答6:
我記得可以
try: ......except KeyboardInterrupt: exit()
相關(guān)文章:
1. docker綁定了nginx端口 外部訪問(wèn)不到2. docker網(wǎng)絡(luò)端口映射,沒(méi)有方便點(diǎn)的操作方法么?3. docker容器呢SSH為什么連不通呢?4. thinkphp5.1學(xué)習(xí)時(shí)遇到session問(wèn)題5. nignx - docker內(nèi)nginx 80端口被占用6. angular.js - angular內(nèi)容過(guò)長(zhǎng)展開收起效果7. macos - mac下docker如何設(shè)置代理8. php - 第三方支付平臺(tái)在很短時(shí)間內(nèi)多次異步通知,訂單多次確認(rèn)收款9. docker images顯示的鏡像過(guò)多,狗眼被亮瞎了,怎么辦?10. 前端 - ng-view不能加載進(jìn)模板
