Reputation: 35
I have a big question I couldn't get answer from the web about sockets in python. I'm making a simple client program (python) based on socket: Connecting to a server.
I would like to make a function that its purpose is just to try to connect to the server, otherwise the application will not work. Because I had trouble with "global" socket variable across the whole class, I decided to make a local socket variable inside my main and pass it through all functions.
I wanted to make sure that I understand it 100% : Should I return the socket from the function that's trying to connect to the server ( otherwise sleeps for 0.5 a second and tries again ) OR I don't need to return the socket at all and the socket variable itself will be updated ?
UPDATE
#will try to connect to the server
def try_connecting_to_server(socket_to_server):
connected = False
while not connected:
try:
socket_to_server.connect((HOST, PORT)) # connect to the server
connected = True
except:
print "couldn't connect to server, sleeping for 0.5 seconds"
time.sleep(0.5)
return socket_to_server
def main():
# start the socket to the server
socket_to_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # setup the socket for future use
try:
socket_to_server = try_connecting_to_server(socket_to_server)
handle_missions(socket_to_server) # pass the socket
except:
print "encountered an error"
finally:
socket_to_server.sendall(PROTOCOL_CLOSE_KEY)
socket_to_server.close()
if __name__ == "__main__":
main()
Upvotes: 0
Views: 911
Reputation: 137398
def try_connecting_to_server(socket_to_server):
connected = False
while not connected:
try:
socket_to_server.connect((HOST, PORT)) # connect to the server
connected = True
except:
print "couldn't connect to server, sleeping for 0.5 seconds"
time.sleep(0.5)
return socket_to_server
There is no reason for this function to return socket_to_server
.
Since a socket
object is mutable, any changes to it inside the function (e.g. connecting it to a server) are visible to the function which called it.
You can verify that by making this change in main()
:
returned_sock = try_connecting_to_server(socket_to_server)
if returned_sock is socket_to_server:
print "They refer to the exact same object!"
See How do I pass a variable by reference?
Upvotes: 1