0

I have a basic socket server connection running with the general:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((hostHost, hostPort))
s.listen(10)
conn, addr = s.accept()

But whenever I try to call a

print(conn.send("Hello World"))

it returns an error:

NameError: global name 'conn' is not defined

I don't understand why this happens, can someone explain please? (I did this in a Tkinter window but I removed that code to simplify this).

NB: I have imported all the correct libraries, and if I change it to s.send, then the same error occurs.. I called the send() in another function:

def send_Button():
        myMsg = "ME: " + text.get()
        msg = text.get()
        conn.send(msg)
        textBox.insert(END, myMsg + "\n")
        textEntry.delete(0, END)
        textBox.yview_pickplace("end")

Thank you.

Blade
  • 190
  • 4
  • 12
  • 1
    Show where you're calling `print(conn.recv(1024))` in relation to the code you posted as a [mcve]. If you're calling it from a different function, it won't be in scope. – Carcigenicate Jul 14 '18 at 19:02
  • You simplified too much. There is no `conn` variable defined anywhere in your code, and since you also don't `import` anything, the error makes perfect sense. – Jongware Jul 14 '18 at 19:04
  • Yeah i did call it in another function: I have one function which initiates the server ^^ and another which is called when a button is pressed: def send_Button(): myMsg = "ME: " + text.get() msg = text.get() conn.send(msg) textBox.insert(END, myMsg + "\n") textEntry.delete(0, END) textBox.yview_pickplace("end") – Blade Jul 14 '18 at 19:05
  • I edited my original post, it explained – Blade Jul 14 '18 at 19:08

1 Answers1

0

You should look at the line number given in the error message. A variable goes out of scope whenever you leave a function. Your code seems to leave out some details as to where conn is defined and referenced, but here is a short example that will give the same error, and hopefully give some guidance on where to look in your own program.

def make_var():
    some_var = 1      # initialize a variable some_var

def print_var():
    print some_var    # Print a variable called some_var

make_var()
print_var()     # some_var has already gone out of scope, the program crashes

# now let's define some_var in the global scope
some_var = "yay, this works!"
print_var()      # this print's "yay, this works"
Ben Jones
  • 652
  • 6
  • 21