Multiple threaded socket connections/queues
<p>SocketClientThread Reference: <a href="http://eli.thegreenplace.net/2011/05/18/code-sample-socket-client-thread-in-python/" rel="nofollow">http://eli.thegreenplace.net/2011/05/18/code-sample-socket-client-thread-in-python/</a></p>

<p>Eli provided this generic example of how to manage a socket client inside a thread, and communicate to the main scope with the Queue module. (thanks again Eli!)</p>

<p>One thread works great, but I'm trying to do is manage multiple SocketClientThread objects at the same time.</p>

<p>After connecting, when I try to send data to the second object, it is telling me that SocketClientThread.socket has no sendall attribute, so I think that the socket gets nulled out.</p>

<p>The server of both 1 and 2 receive the connections successfully, but it is the send command of the second server that triggers the error.</p>

<p>How can I re-use this class with multiple objects?</p>

<p>Here's the output:</p>

<pre><code>$ python testmodule.py
('sct1: ', 1, None)
('sct1: ', 1, 'tuxy')
('sct2: ', 1, None)
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner
    self.run()
  File "testmodule.py", line 59, in run
    self.handlers[cmd.type](cmd)
  File "testmodule.py", line 115, in _handle_SEND
    self.socket.sendall(header + cmd.data)
AttributeError: 'NoneType' object has no attribute 'sendall'
</code></pre>

<p>And here's my code trying to open up both:</p>

<pre><code>if __name__ == "__main__":
    sct1 = SocketClientThread()
    sct1.start()
    sct1.cmd_q.put(ClientCommand(ClientCommand.CONNECT, ('', 50007)))
    reply = sct1.reply_q.get(True)
    sct1.cmd_q.put(ClientCommand(ClientCommand.SEND, "hellothere from sct1"))
    reply = sct1.reply_q.get(True)
    print('sct1: ', reply.type, reply.data)
    sct1.cmd_q.put(ClientCommand(ClientCommand.RECEIVE, "hellothere from sct1"))
    reply = sct1.reply_q.get(True)
    print('sct1: ', reply.type, reply.data)

    sct2 = SocketClientThread()
    sct2.start()
    sct2.cmd_q.put(ClientCommand(ClientCommand.CONNECT, ('', 50008)))
    reply = sct2.reply_q.get(True)
    print('sct2 connect: ', reply.type, reply.data)
    sct2.cmd_q.put(ClientCommand(ClientCommand.SEND, "hellothere from sct2"))
    reply = sct2.reply_q.get(True)
    print('sct2 send: ', reply.type, reply.data)
    sct2.cmd_q.put(ClientCommand(ClientCommand.RECEIVE, "hellothere from sct2"))
    reply = sct2.reply_q.get(True)
    print('sct2: ', reply.type, reply.data)

    #close connection 1
    sct1.cmd_q.put(ClientCommand(ClientCommand.CLOSE))
    reply = sct1.reply_q.get(True)
    print('sct1 close: ', reply.type, reply.data)

    #close connection 2
    sct2.cmd_q.put(ClientCommand(ClientCommand.CLOSE))
    reply = sct2.reply_q.get(True)
    print('sct2 close: ', reply.type, reply.data)
</code></pre>
