Why am I unable to use sockets in python to connect to a server with an ip address and port number?

Issue

This Content is from Stack Overflow. Question asked by Filip Surbek

I have been searched all over the web and all examples with an ip address and port number connect like how I’ve done it.

 def on_connect(self):
    if self.button1['text'] == "Connect":
        try:
            #host = str(self.ltext1.get())
            #port = int(self.spin1.get())
            host="127.0.0.1"
            port=502
            tcpsocket= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_adress = (host,port)
            tcpsocket.connect(server_adress)
            print("sdsd")
            self.button1['text'] = "Disconnect"
        except:
            print("failed")
    else:
        tcpsocket.close()
        self.button1['text'] = "Connect"

For me I have a server open at that port and I have successfully connect to it using a C++ client application but when I connect with the same ip address and port number it enter the except meaning the connect failed and my server does not even inform me of any attempt to connect(it does for the C++ client).

Where have I gone wrong in my code or what could possibly be the problem. I also disconnect and close the C++ client application to free up the port for my client.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?