Thursday, March 26, 2015

Socket programming for multiple requests and respondses

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

TCPClient.py
from socket import *
serverName = 'localhost'
serverPort = 12029
c=1
while c==1:
    clientSocket = socket(AF_INET, SOCK_STREAM)
    clientSocket.connect((serverName, serverPort))
    sentence = raw_input('Input lowercase sentence:')
    clientSocket.send(sentence)
    modifiedSentence = clientSocket.recv(1024)
    print 'From Server:', modifiedSentence
    
clientSocket.close()