title: Python sockets; sending from client receiving on server
body: <p>I am trying to send messages on TCP/IP all on host machine. This is working, although for some reason the socket needs to be re-instantiated for every new message on the client side only. For example here is a basic client that sends three separate messages:    </p>
  
  <pre><code>import socket
  
  
  host = '127.0.0.1'
  
  class Client:
      def __init__(self):
          self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  
      def connect(self):
          self.sock.connect((host,12347))
  
      def send(self,message):
              self.sock.sendall(message)
      def close(self):
          self.sock.close()
  
  
  if __name__ == "__main__":
  
      message1 = "I am message 1"
      message2 = "I am message 2"
      message3 = "I am message 3"
  
      #exp = Client()
      #exp.connect()
  
      for i in range(0,3):
          try:
              exp = Client()
              exp.connect()
              if i == 0:
                  txt = message1
              elif i == 1:
                  txt = message2
              elif i == 2:
                  txt = message3
                  exp.send(txt)
                  exp.close()
  
              print i
              exp.send(txt)
  
          except:
              pass
  </code></pre>
  
  <p>and the server that receives:</p>
  
  <pre><code>#!/usr/bin/env python
  
  import socket
  
  
  class communication:
  
  
    def __init__(self):
      try:
  
        host = '127.0.0.1'
  
        self.Server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  
        self.Server.bind((host,12347))
  
        self.Server.listen(1)
  
      finally:
  
        print "setup finished"
  
  
  
    def recieve(self):
  
      (connection, client_address) = self.Server.accept()
  
      data = connection.recv(128)
  
      return data
  
  
  
    def close(self):
  
      self.server.close()
  
  
  
  
  
  if __name__ == "__main__":
  
  
  
      exp = communication()
  
  
  
      while True:
  
          try:
  
              (connection,client_address) = exp.Server.accept()
  
              message = connection.recv(128)
  
          finally:
  
              print message
  
  
  
          if message == "I am message 3":
  
            exp.close()
  </code></pre>
  
  <p>You see how I re-call the Client class in each iteration of the for loop. This seems to be necessary for sending messages 2 and 3. If the socket is instantiated only once at the start of the main code along with the connect() function, then the server hangs on the recv() after the first message has been sent. </p>
  
  <p>I can't understand why this is happening and the socket only needs to be setup once on the server side. I am doing something wrong, or is this normal? </p>
  
  <p>Thanks! </p>