2

I have a disconnect button and a connect button on my client. When I click the disconnect button and then the connect button I get this: OSError: [WinError 10038] An operation was attempted on something that is not a socket

The disconnect button is coded like this:

def Disconnect():
    s.shutdown(socket.SHUT_RDWR)
    s.close()

And the connect button is this:

def Join1():
    print("CONNECTING TO: " + host + "...")
    try:
        s.connect((host, port))
        print("CONNECTING TO: " + host + " ESTABLISHED!")

        statusbar_status = "Connected"
        startrecv = Thread(target=returnrecv)
        startrecv.start()

Why can't I connect again after I click the disconnect button? Is it impossible to reopen the socket? I've been stuck on this problem for like a month now and I can't understand why..

Michael L
  • 163
  • 1
  • 1
  • 8

1 Answers1

2

After closing a socket, you cannot reuse it to share other data between Server and Client. From Python Docs, about close() method:

Close the socket. All future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.

So you would need to create a new socket object every time you try to connect (in your join1() function which would look something like this:

def Join1():
    global s     # i would recommend using classes instead
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      # your socket object
    print("CONNECTING TO: " + host + "...")
    try:
        s.connect((host, port))
        ...
Stevo Mitric
  • 1,570
  • 18
  • 19
  • Thank you sooo much, I didn't know about the global keyword! (fairly new to programming). Can you explain why it would be better to use classes instead of global? – Michael L Dec 29 '18 at 21:48
  • 1
    Using global variables in any language is considered "bad". Check out [this](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil) post. OOP provides a clear modular structure for programs and is much easier to read/write once you get used to it (especially if you're coding GUI app). – Stevo Mitric Dec 29 '18 at 22:52
  • @StevoMitric, I cannot wrap my head around, how to address the same connection object from different controls if we use classes? Even if we have a class with two methods - open and close, how does "close control" see the connection object? – garej Mar 20 '23 at 07:11