Hello I am trying to port some C code to python. I haven’t used python in a few months so feel a bit rusty.
Wondering how I can do this. I need to be able to use the send value of the sock object in createConnection function with out making the sock object global.
any ideas?
*cheers
Example code
def createConnection(host, port, tcpTimeout):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
sock.connect((host, port))
return sock
def useConnectionOne():
sock = createConnection("<Some IP>", <Some Port>, 5)
sock.send("Hello world")
def useConnectionTwo():
sock = createConnection("<Some IP>", <Some Port>, 5)
sock.send("Hello again world")
You either need to make the socket objects global so they can be re-used, or attach them to some other object / container to keep track of them. You could do something like this:
Then you can send with:
Without some outer container though, your socket objects leave scope and are garbage collected when the function that creates them returns.
If I misunderstand you somehow, and you want a single connection object and the ability write two methods that use it separately, create a class that contains the connection:
Hopefully that gives you an idea you can build from.