I need to open a socket connection in a new thread. That connection needs to stay open. Then I need to be able to send data to the socket from the main scope.
I have a feeling what’s happening with my code is that the thread is completing & closing the socket right away and then there’s no properties to send data to.
How can I keep the thread & socket opened to receive data to send out from the main scope?
(If I take the threading out of this, it works fine.)
Below is the code and output I’m working with.
Here is the output from the shell:
$ python test.py
Traceback (most recent call last):
File "test.py", line 25, in <module>
packet = mt.sendData('somedata')
File "test.py", line 19, in sendData
self.mySocket.send(myString)
AttributeError: 'NoneType' object has no attribute 'send'
And here is the code
note line 19 is: self.mySocket.send(myString)
line 25 is: packet = mt.sendData('somedata')
import threading
import socket
class MyTest(threading.Thread):
def __init__(self, host, port):
self.host = host
self.port = port
self.mySocket = None
threading.Thread.__init__(self)
def run(self):
#open socket
self.mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.mySocket.connect( ( self.host, self.port ) )
self.mySocket.setblocking(1)
def sendData(self, myString):
# send data to socket
self.mySocket.send(myString)
packet = self.mySocket.recv(4096)
mt = MyTest('127.0.0.1', 50001)
mt.start()
packet = mt.sendData('somedata')
You may find the example in this post useful – it demonstrates a thread that perform socket communication receiving commands from another thread via
Queueobjects. It’s a rather generic sample, well documented (both in comments and the linked blog post) and you can easily adapt it for any specific purpose.