title: Keyboard interrupt, sockets and Threads
body: <p>I'm working on an interface that communicates using sockets. I need to use Threads in order to receive and send data at the same time.</p>
  
  <p>The below code is a cut down version of the module that continuously sends data.</p>
  
  <p>My issue is that during development, I need to start and stop this frequently, but it seems threads makes it impossible to stop the application like you can a normal script. The process needs to be killed in process manager in order to restart it.</p>
  
  <p>I have a feeling I am misunderstanding something.</p>
  
  <p>I've looked around but I'm seeing loads of inconsistent answers which I've tried to implement to no avail. I've tried handling the KeyboardInterrupt exception and that doesn't work.</p>
  
  <p>Any ideas?</p>
  
  <pre><code>import socket
  import sys
  import threading
  
  running = True
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  
  server_address = ('localhost', 50000)
  print ('connecting to %s port %s' % server_address)
  sock.connect(server_address)
  
  class TelemetryPacket:
      state = "N/A" 
  
      def __init__(self, stringvalue):
          self.state = stringvalue
  
      def serialise(self):
          return "%s" % (self.state)
  
  def send(running):
      try:
          while (running):
              telemetry = TelemetryPacket(0).serialise()
              sock.sendto(telemetry.encode('utf-8'), server_address)
      except KeyboardInterrupt:
          print ("threads successfully closed")
          running = False
  
  def recv(running):
      try:
          while (running):
              data = sock.recv(1)
              if (data):
                  print("data received: %s" % data)
      except KeyboardInterrupt:
          print ("threads successfully closed")
          running = False
  
  a = threading.Thread(target=send, args=(running,))
  a.start()
  
  b = threading.Thread(target=recv, args=(running,))
  b.start()
  </code></pre>