Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadingTCPServer won't exit when client connected

I am running a simple echo socketserver and whenever there is a client connected, ctrl C doesn't exit/terminate the server. Instead it "hangs" until client disconnects from the socket. I have read somewhere that this is due to there being a thread alive even after the main thread has been terminated. How do I fix this issue?

Python code (excuse some of the indents, it did not copy paste well):

import SocketServer
from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler
import sys
import time
import socket
import os

class ThreadingTCPServer(ThreadingMixIn, TCPServer):
     pass

class RequestHandler(StreamRequestHandler):

    def handle(self):
        print str(self.client_address) + 'connected'
        data = "foo"
        while data != "":
            try:
                data = self.rfile.readline().rstrip('\n')
            except:
                self.request.close()
                print 'Socket Error'
                break
                print data
            try:
                self.wfile.write("OK\n")
            except socket.error:
                data = ""
        print 'Handler Exiting'
        self.request.close()

    def finish(self):
        print 'Client ' + str(self.client_address) + ' Disconnected'

if __name__ == '__main__':
    PORT = 80
    print 'Starting Server on port: ' + str(PORT)
    ThreadingTCPServer.allow_reuse_address = True
    server = ThreadingTCPServer(("", PORT), RequestHandler)
    try:    
        server.serve_forever()
    except KeyboardInterrupt:
        print "\nServer Terminated"
        server.shutdown()
        sys.exit()

All responses are appreciated, thank you for your time!

like image 923
skyguy126 Avatar asked Sep 15 '26 09:09

skyguy126


1 Answers

Try doing this at the start of your program:

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

What it does is to restore the default before for Ctrl-C (SIGINT), which is to terminate the program immediately.

like image 184
John Zwinck Avatar answered Sep 17 '26 23:09

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!