Reputation: 189
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")
Upvotes: 1
Views: 2826
Reputation: 48028
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:
Connections = {}
Connections['host1'] = createConnection("<Some IP>", <Some Port>, 5)
Connections['host2'] = createConnection("<Some Other IP>", <Some Port>, 5)
Then you can send with:
Connections['host1'].send("Hello World")
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:
class ConnManager(object):
def __init__(self, host, port, timeout)
self._conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
self._conn.connect((host, port))
def sendOne(self, data):
self._conn.send(data)
def sendTwo(self, data):
self._conn.send(data)
Hopefully that gives you an idea you can build from.
Upvotes: 1