0

I have an issue where i try to have the client loop till it receives a connection from server. When i try to put the socket as global variable. Then use start to establish a connect, it connects. but when i use send with a valid data variable, i get this error: Socket is not connected. this works only if i put all the code in start and it'll send information. This will code work if i start the server before the client, but not the other way around. Trying to get it working for any scenario.

#global variable definition
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def start(host, port):
    connected = False

    while not connected:     
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host, port))
            connected = True
            print("Connected")
        except:
            print("connecting again!")
            sleep(5)

#i do put a valid json to send!
def send():
    try:
        s.sendall(json.dumps(data).encode('utf-8'))
  • Your `start` method creates a new socket, connects it, and then throws it away. Remove the `s = socket.socket(...)` line or add `global s` at the top of the function. – Aran-Fey Mar 29 '18 at 08:56
  • 1
    Possible duplicate of [Using global variables in a function other than the one that created them](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) – Aran-Fey Mar 29 '18 at 08:57
  • Declaring global inside the function helped. Thanks – ReeLSpirit Mar 31 '18 at 07:51

1 Answers1

0

You should not rely on global variables. Return the connected socket and use it in send:

def start(host, port):
    while True:     
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host, port))
            print("Connected")
            return s
        except IOError:
            print("connecting again!")
            sleep(5)

#i do put a valid json to send!
def send(s, data):
    s.sendall(json.dumps(data).encode('utf-8'))

s = start(HOST, PORT)
send(s, data)
Daniel
  • 42,087
  • 4
  • 55
  • 81