Thursday, March 26, 2015

Socket programming for 2 clients to talk each other through the server

TCPServer.py
from socket import *
serverPort = 12095
print 'The server is ready to receive'
c=1
while c==1:
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.bind(('', serverPort))
    serverSocket.listen(2)
    connectionSocket1, addr1 = serverSocket.accept()
    connectionSocket2, addr2 = serverSocket.accept()
    sentence1 = connectionSocket1.recv(1024)
    sentence2 = connectionSocket2.recv(1024)
    capitalizedSentence1 = sentence1.upper()
    capitalizedSentence2 = sentence2.upper()
    connectionSocket2.send(capitalizedSentence1)
    connectionSocket1.send(capitalizedSentence2)

connectionSocket.close()

TCPClient1.py
from socket import *
serverName = 'localhost'
serverPort = 12095
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()

TCPClient2.py
from socket import *
serverName = 'localhost'
serverPort = 12095
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()