Oliv
Oliv

Reputation: 148

TCP Multithread Python

I am new to Python and also Thread and I'm trying to make a TCP server in python. The client connect good to the server but can only put 1 command, then it crash, here is the code :

serverSocket = socket(AF_INET, SOCK_STREAM)


def Main():
    serverPort = 7722
    print("The server is ready to receive on port", serverPort)
    serverSocket.bind(('', serverPort))
    serverSocket.listen(1)


def start_socket(connectionSocket):
    while True:
        print('Connection requested from', clientAddress)
        client_code_number = connectionSocket.recv(2048)
        server_code_number = client_code_number.decode()
        if (server_code_number == "1"):
            print("Command 1\n\n")
            message = connectionSocket.recv(2048)
            modifiedMessage = message.decode().upper()
            connectionSocket.send(modifiedMessage.encode())
        connectionSocket.close()


if __name__ == '__main__':
    Main()
    while True:
        (connectionSocket, clientAddress) = serverSocket.accept()
        os.system('cls')
        print('connexion from: ' + str(clientAddress))
        _thread.start_new_thread(start_socket, (connectionSocket,))
serverSocket.close()

Here is the client :

def start_socket():
    init_text()
    choice_number = input('Input option: ')
    #GET THE USER NUMBER
    clientSocket.send(choice_number.encode())
    while True:
        if choice_number == "1":
            sentence_caps = input('Input sentence: ')
            clientSocket.send(sentence_caps.encode())
            modifiedMessage = clientSocket.recv(2048)
            print('\nReply from server:', modifiedMessage.decode())
            start_socket()
        else:
            start_socket()

And here is my error :

File "BasicTCPServer.py", line 33, in start_socket
client_code_number = connectionSocket.recv(2048)
OSError: [Errno 9] Bad file descriptor

Upvotes: 0

Views: 89

Answers (1)

cup
cup

Reputation: 8237

The root cause is that the socket is being closed.

def start_socket(connectionSocket):
    while True:
        print('Connection requested from', clientAddress) # <-- where does client address come from
        client_code_number = connectionSocket.recv(2048)  # <-- this works the first time round
        server_code_number = client_code_number.decode()
        if (server_code_number == "1"):
            ...
        connectionSocket.close()  # <-- this closes the socket

Your code is complaining about the second time through the loop. connectionSocket has been closed, so it is a bad file descriptor.

Upvotes: 1

Related Questions