I need to modify the below code to send a string from client to server, it needs
ID: 3735429 • Letter: I
Question
I need to modify the below code to send a string from client to server, it needs to ask the server to send back the reverse string to the client. For example 1. Client send "12345" to server 2. Server send "54321" back to client. It needs to be written in Python. Thank you!
editable code:
#import socket module
from socket import *
import sys # In order to terminate the program
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
#Fill in start
serverHost = '192.168.0.103'
serverPort = 6789
serverSocket.bind((serverHost,serverPort))
serverSocket.listen(5)
#Fill in end
while True:
#Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept() #Fill in start #Fill in end
try:
message = connectionSocket.recv(4096) #Fill in start #Fill in end
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.readlines() #Fill in start #Fill in end
#Send one HTTP header line into socket
#Fill in start
connectionSocket.Send("HTTP/1.1 200 OK Content-Type: text/html ")
connectionSocket.Send(" ")
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.send(" ".encode())
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill in start
connectionSocket.send("HTTP/ 1.1 404 Not Found ")
connectionSocket.send("Content-Type: text/html ")
connectionSocket.send(" ")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html> ")
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
sys.exit()#Terminate the program after sending the corresponding data
Explanation / Answer
// Server.py code is for python 2.7 //
import socket
from thread import *
import threading
def func(c):
while True:
data = c.recv(1024)
if not data:
print('Invalid Data')
break
command = c.recv(100)
data = data[::-1]
if(command == "y") :
print("sending reverse string")
c.send(data)
c.close()
host = "127.0.0.1"
port = 9981
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("socket binded to port")
s.listen(5)
print("socket is listening")
while True:
c, addr = s.accept()
print("Connected established")
start_new_thread(func, (c,))
s.close()
// client.py
import socket
host = '127.0.0.1'
port = 9981
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.connect((host,port))
mess = raw_input("Enter String to send : ")
soc.send(mess)
command = raw_input("Do you want to get reverse string y/n :")
if(command == "y" ) :
soc.send(command)
data = soc.recv(1024)
print("reversed string is : " + data)
soc.close()