Socket is not defined when I have created one

Viewed 387

I have a program that just sends messages to a server through a tkinter interface. I am using various subprograms to run basic things like starting a new connection and sending a message. The only issue is, it keeps on coming up with the name error "clientsocket is not defined" when the user has to go through another subprogram to establish the connection.

I have tried moving the subprograms around, making clientsocket a global variable and I have double-checked that my names are correct. The code I got these subprograms from functions fine (a chatting program that runs in the console that I made a while ago) so it must be how I have structured the program.

Here is all the subprograms that deal with sockets

def send_msg(): # Sends a message to the server (called from tkinter button)
        try:
            Csend = field.get("1.0", "end-1c")
            Csend = str(Csend)
            clientsocket.send(Csend.encode())

            field.delete()
            field.insert(END, "")
        except error as err:
            Csend = field.get("1.0", "end-1c") # 1.0 - Line one, char zero
            print(f"Can't send message \"{Csend}\": Not connected to a server")
            print(err)

    def new_connection():
        # Tkinter code goes here
        def connect_server(): # Tries to connect to the server
            try: # This runs the first check, if there is an existing connection
                clientsocket.close()
            except:
                print("No existing connection")

            try: # Runs the second check, if it can connect using the info
                clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

                host = host_ent.get() # Gets STR of host IP
                port = port_ent.get() # Gets STR of port
                port = int(port) # Converts port to INT

                clientsocket.connect((host, port)) # Connects to the server
            except:
                print("Could not connect, incorrect inputs?")

    def disconnect_server():
        try:
            clientsocket.close()
        except:
            print("No existing connection")

All of these subprograms are called from tkinter menubars or buttons.

I am quite new to sockets, so if any of the code is beginner-tier then I am sorry.

Thank in advance for any help!

1 Answers

The problem is, that you don't define your socket global, only local in you function. you should add global clientsocket under the header of every function you use your clientsocket.

Related