Python Sockets use function instead of global socket call


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?


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:

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.


  • Python Server socket.error: [Errno 92] Protocol not available
  • python 3 median-of-3 Quicksort implementation which switches to heapsort after a recursion depth lim
  • connect() does not return
  • How do I only display one element and not two based on lowest InternalPartyID?
  • Update-rc.d custom script running too late, and also runs at shutdown
  • Access a nested object array
  • how to group array of nsdictionary according to the value inside the element
  • Parse “key cannot be nil” error on [PFObject saveInBackground] (Cocoa)
  • How to use boost program_options to read an integer array?
  • Prestashop : loop on $product->save() method
  • e2e testing angular 7: Failed: Cannot read property 'fetchData' of undefined
  • How to get same result as following Mysql query from Solr?
  • NSURLCredentialStorage default credential not used automatically
  • In GTK, how do I change the localized language text on the UI while it's running?
  • Controlling prompt for command line
  • Sending int from java to c
  • Swift 3 - CFHostScheduleWithRunLoop crash
  • Server does not respond to new clients using select(), cpp
  • App Script: How to view PDF of Google Sheet after function to save to Google Drive?
  • Pretty good heuristic evaluation rules for big TicTacToe 5x5 board
  • Receive .txt file from parse.com and place in textview
  • Creating and binding socket on Mac OS Hight Sierra
  • Connection reset by peer [errno 104] in Python 2.7
  • Winsock returns 10061 on connect only to localhost
  • GetQueuedCompletionStatus blocks forever
  • Need help manipulating an array in ruby
  • Ruby: Invert a hash to also preserve non unique values
  • How to read data from socket connection - android
  • Cannot send user message with Spring Websocket
  • openssl handshake failed
  • How to resolve docker host names (/etc/hosts) in containers
  • Error in making a socket connection
  • Dynamically switching connect in Modelica
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • Redux Form - Not able to type anything in input
  • Get history of file changes from TFS to implement custom “blame”-behaviour of exceptions
  • Microsoft Visual Studio Community 2015 always crashes in Windows 10 if swithed to Visual FoxPro
  • need help with bizarre java.net.HttpURLConnection behavior
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?