用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都不能终止,请问要怎么终止程序?
Ctrl + C
在启动线程之前,添加
setDaemon(True)
这样 <C-c> 的中断信号就会被 rasie。
Close the cmd command window and reopen a cmd, this is what I did.
You can use the signal module. When pressing Ctrl+C, capture the information and then exit.
I can remember it