title: Sending messages to all clients
body: <p>This is probably very simple socket message exchange programming, but with my flimsy idea on socket and all, I could not really make it work properly so I'm reaching out for help. </p>
  
  <p>Scenario : Two clients send messages. First one sends <code>Halo</code> and <code>Seeya</code>. <strong>After</strong> the first sends those messages, the second sends <code>Hello</code> and <code>Bye</code> (This client will just time sleep 6 secs to keep this order). To all messages, server replies with <code>(original msg), client (number)!</code>and a reply message is broadcasted to <strong>both</strong> clients.</p>
  
  <p>So ideally, the result on both clients would look like this :</p>
  
  <pre><code>    Halo, client 1!
      Seeya, client 1!
  
      Hello, client 2!
      Bye, client 2 !
  </code></pre>
  
  <p>I couldn't make it to numbering each client, but here is my code that works weird.</p>
  
  <h1>server</h1>
  
  <pre><code>    import socket             
  
      clients = []
  
      # send msgs to every client
      def broadcast(message):          
          for client in clients : 
              client.send(message)
  
      # connection part
      s = socket.socket()         
      s.bind(('127.0.0.1', 7070)) 
      s.listen(2)    
  
      while True:
          c, addr = s.accept()
          if c:
              clients.append(c)
          msg = c.recv(1024).decode()
          msg += ', client!'
          broadcast(msg.encode())
  </code></pre>
  
  <h1>client1</h1>
  
  <pre><code>    ### here goes connection part ###
  
      s.send(("Halo").encode())
      print(f"server = {(s.recv(1024)).decode()}")
  
      # I've tried adding socket closing/connection part here
  
      s.send(("Seeya").encode())
      print((s.recv(1024)).decode())
  
      time.sleep(3)
      s.close()
  </code></pre>
  
  <h1>client2 - first connected, but waits 6 secs for message order</h1>
  
  <pre><code>    ### here goes connection part ###
  
      time.sleep(6)               # waits for message order
      s.send(("Hello").encode())
      print(f"server = {(s.recv(1024)).decode()}")
  
      # I've tried adding socket closing/connection part here
  
      s.send(("Bye").encode())
      print((s.recv(1024)).decode())
      time.sleep(3)
      s.close()
  </code></pre>
  
  <p>The result I get is...</p>
  
  <pre><code>    # On client 1 side 
      Halo, client!                  # no Seeya, Hello, Bye
                                     # connection isn't closed
  
      # On client 2 side
      Hello, client!                 # no Seeya, Bye
      Halo, client!                  # connection is closed
  </code></pre>