I'm new to socket programming and trying to get back into python. I wanted to write a simple TCP program which will continuously maintain a connection until some end state is reached, in this case "close" is sent by the client.
This works fine for the first iteration, but it freezes on the second thing I send and I'm not sure why. Could someone please explain why my program freezes or how better implement this?
TCPServer.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print('The server is ready to recieve')
while True:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024).decode()
if(sentence == "close"):
connectionSocket.close()
capSentence = sentence.upper()
connectionSocket.send(capSentence.encode())
TCPClient.py
from socket import *
serverName = 'localhost'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
while(1):
sentence = raw_input('input sentence: ')
if(sentence == "close"):
break
clientSocket.send(sentence.encode())
retSentence = clientSocket.recv(1024)
print('From server; ', retSentence.decode())
clientSocket.close()