Jose Ortiz
Jose Ortiz

Reputation: 725

Python client keeps loosing connection to tcp socket connection

I am writing a python server client using TCP connecton SOCK_STREAM.

I am able to make one connection from the client and the server returns the response.

The second time the connection is lost from what I am seeing

Here is the server code

from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 62175
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print('The server is ready to receive information')
connectionSocket, addr = serverSocket.accept()
while True:
       sentence = connectionSocket.recv(1024).decode()
       capitalizedSentence = sentence.upper()
       connectionSocket.send(capitalizedSentence.encode()) 
       connectionSocket.close()

Here is the code for the client

from socket import *
import sys
import re

serverName = 'localhost'
serverPort = 62175
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
done = False
while done == False:
    sentence = input("Input a lowercase sentence: ")
    try:
        inputValue = int(sentence)
        print("Input data is an integer, suppose to be a string, Run the program again")
    except ValueError:     
        try:
            if(regex.search(sentence) == None):   
                if (sentence.lower() == "quit"):
                    done = True
                    clientSocket.close()
                elif (sentence == ""):
                    print("There wasn't any input detected. Try again")
                else:
                    clientSocket.sendall(sentence.encode())
                    modifiedSentence = clientSocket.recv(1024)
                    print(modifiedSentence.decode())
                    print(done)
            else:
                print("String contains special characters, Try again")
        except OSError as err:
            print("OS error: {0}".format(err))

Here is the output and error when I enter a second input

Input a lowercase sentence: test
TEST
False
Input a lowercase sentence: test
OS error: [WinError 10053] An established connection was aborted by the software in your host machine

Thank you for the assist

Upvotes: 0

Views: 163

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123481

Your server closes the connection inside the loop but tries to communicate through the closed socket:

connectionSocket, addr = serverSocket.accept()
while True:
       sentence = connectionSocket.recv(1024).decode()
       ...
       connectionSocket.close()

To handle multiple recv and send within the connection you should call close only when you are actually done:

connectionSocket, addr = serverSocket.accept()
while True:
       sentence = connectionSocket.recv(1024).decode()
       ...
connectionSocket.close()

Upvotes: 1

Related Questions