1
votes

I'm trying to create a client/server console game, but I'm having trouble keeping the socket alive, it seems to be closing before I've called close() and I can't figure out why.

I've read the thread here but I have called connect() outside of the while loop since the logic of that already made sense to me before I attempted to run it, but I'm still getting the error from the server shell though:

ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

So far I'm not getting an error on the client shell, it just exits running right after launching which is also when the server error occurs.
After fixing mistakes noted in the comments, the client now also shows an error stating that connected is undefined when attempting to start the while loop but should be since Connect() is run before entering the loop which should have set connected = True thus the loop should run but does not. I doubt this is related to the server issue at all, but what maybe the problem here?

I'll put the code for both below:

Client

import socket

def GetData():
    data = s.recv(1000).decode()
    if (data == "closing"):
        connected = False
    else:
        print(data)

def SendData():
    tdata = input("")
    s.send(data.encode())


def Connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("127.0.0.1", 2222))
    connected = True


global connected
Connect()

while (connected == True):
    GetData()
    if (connected == False):
        s.close()
        break
    SendData()

Server

import socket
import random

def TheMainGame():
    print ("started TheMainGame")  # Remove after debug
    def within(val, goal):
        print ("Runing 'within' function")  # Remove after debug
        i = abs(val - goal)
        if (i <= 5):
            return True
        else:
            return False

    def Guess():
        print ("Running 'Guess' function")  # Remove after debug
        while True:
            print ("Entered while loop")  # Remove after debug
            data = "What is your guess?"
            c.send(data.encode())
            print ("Sent data")  # Remove after debug
            t = c.recv(1000).decode()
            print ("Got data")  # Remove after debug
            if (t == x):
                data = "Correct!"
                c.send(data.encode())
                data = "closing"
                c.send(data.encode())
                c.close()
                break
            elif (within(t,x) == True):
                data = "You're close!"
                c.send(data.encode())
            elif (within(t,x) == False):
                data = "Try again"
                c.send(data.encode())
            else:
                data = "There was an error computing the value"
                c.send(data.encode())
                c.close()
                break

    x = random.randrange(1, 20, 1)
    Guess()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 2222))
s.listen(5)
global data
while True:
    (c,a) = s.accept()
    print("Received connection from", a)  # Remove after debug
    data = "Hello %s" %a[0]  # Remove after debug
    c.send(data.encode())  # Remove after debug
    TheMainGame()

The error in the server shell relates to line 19 which is why the server attempts to ask the client the question, which is also the second time it attempts to send data to the client but the attempt never successfully happens, which is why I think the socket is being closed even though I never told it to anywhere before that point since it hasn't even been able to check if t == x. What is causing the socket to close?

1
You've misspelled connected in Connect() in your client code. Also, if you intend to assign to a global variable, you must use the global keyword with the variable name in the function scope.Joel Cornett
@JoelCornett Oh, so I did! After fixing that, I made connected global (I'll edit my question to reflect the change) and now I'm getting an error in the client too at the while loop stating connected is not defined, but it should be since I ran Connect() which would set it to True before entering the loop...PurplProto
@JoelCornett Problem is now solved, thank you for helping! It would have been solved even quicker if I'd brushed up my knowledge on how global vars work. Again, thanks.PurplProto

1 Answers

1
votes

You're mis-using global in the client.

in the main body you have global connected. This is incorrect.

Instead, at the top of the file put:

import socket
connected = False

Then, in the Connect function, pull in the global scoped variable:

def Connect():
    global connected
    ...

The keyword global is to tell a function to use a variable from the global scope, not to define them.

Note: There are other errors in this code which you will need to look at and address.

  1. You've done the same in server.py
  2. You're trying to reference socket s in the GetData and SendData functions but s is local to within the connect function only (meaning that the connection will drop once the function exists.