title: Python: Synchronize Input and Output Between Threads
body: <p>Currently, I am trying to do a small project with sockets in Python, a two-user chatting system.</p>
  
  <pre><code>import socket
  import threading
  
  #Callback. Print doesn't work across threads
  def data_recieved(data):
      print data
  
  #Thread class to gather input
  class socket_read(threading.Thread):
      sock = object
      def __init__(self, sock):
          threading.Thread.__init__(self)
          self.sock = sock
      def run(self):
          while True:
              data = self.sock.recv(1000)
              if (data == "\quitting\\"):
                  return
              data_recieved(self.sock.recv(1000))
  
  ####################################################################################
  server = False
  uname = input("What's your username: ")
  print "Now for the technical info..."
  port = input("What port do I connect to ['any' if first]: ")
  #This is the first client. Let it get an available port
  if (port == "any"):
      server = True
      port = 9999
      err = True
      while err == True:
          try:
              sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
              sock.bind(('', port))
              err = False
          except:
              err = True
          sock.close()
  
      print "Bound to port #" + str(port)
      print "Waiting for client..."
  
      sock.listen(1)
      (channel, info) = sock.accept()
  else:
      #This is the client. Just bind it tho a predisposed port
      host = input("What's the IP of the other client: ")
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      sock.connect((host, int(port)))
  
  msg = ""
  if (server == True):
      #Use the connection from accept
      reader = socket_read(channel)
  else:
      #Use the actual socket
      reader = socket_read(sock)
  reader.start()
  while msg != 'quit':
      #Get the message...
      msg = uname + ": " + input("Message: ")
      try:
          #And send it
          if (server == True):
              #Use the connection from accept
              channel.send(msg)
          else:
              #Use direct socket
              sock.send(msg)
      except:
          break
  reader.join()
  channel.send("\quitting\\")
  sock.close()
  </code></pre>
  
  <p>(I hope the comments help)</p>
  
  <p>Anyhow, by calling for input at the same time, and getting the other socket's message, I've got a small syncronization issue. I can connect, but when I recieve a message, it doesn't cancel the input statement.</p>
  
  <p>In other words, when I recieve a message, it says this</p>
  
  <pre><code>Message: user: I got a message
  #Flashing cursor here 
  </code></pre>
  
  <p>So that it doesn't cancel the input statement.</p>
  
  <p>Also, I only get every other message.</p>
  
  <p>Any suggestions?</p>