A simple web server and client for python

server:

     Create a connection socket when the client contacts
     Receive HTTP requests from this connection (*)
     Interpret the specific file requested by the request 
     Get the file from the server's file system
     and send the file content
     If the file does not exist, return "404 Not Found" (*)

Client:

    The client can establish a TCP connection with the server

    The client requests a file on the server side through a TCP connection

    Display the content of the introduced file on the client


Note: Before running this file, the server.py directory needs to contain the file folder, which contains the files in the server, and the client can request the files in the file from the server.

readme: First open server.py, open the server         and then open         client.py , enter the         file
        name, including the suffix . py







[python]  view plain copy  
 
  1. import socket  
  2. serverName = '127.0.0.1'  
  3. serverPort = 50008  
  4. clientSocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)  
  5. clientSocket.connect((serverName,serverPort))  
  6. print 'Input the http request:'  
  7. sentence = ''  
  8. while True:  
  9.     tmp = raw_input()  
  10.     sentence = sentence + tmp  
  11.     if(tmp==''):break  
  12. clientSocket.send(sentence)  
  13. receiveSentence = clientSocket.recv(1024)  
  14. print 'From Server:', receiveSentence  
  15. isEnd = raw_input()  
  16. clientSocket.close()  

server.py
[python]  view plain copy  
 
  1. import socket  
  2. import them  
  3.   
  4. serverPort = 50008  
  5. serverSocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)  
  6. serverSocket.bind(('127.0.0.1',serverPort))  
  7. serverSocket.listen(1)  
  8. print 'The server is ready to receive'  
  9. while 1:  
  10.     connectionSocket, addr = serverSocket.accept()       
  11.     sentence = connectionSocket.recv(1024)  
  12.     years =  ''  
  13.     flag = False;  
  14.     for ch in sentence:  
  15.         if(ch == ' ' and flag ==True):break  
  16.         if(flag == True):  
  17.             yrs = yrs + ch;  
  18.         elif(ch== ' '):  
  19.             flag = True;       
  20.               
  21.     path = 'file//' + ans  
  22.     if(os.path.exists(path)==False):  
  23.         connectionSocket.send('404 Not Found')  
  24.     else:  
  25.         file = open( path,'r')  
  26.         while 1:  
  27.             data = file.read(1024)  
  28.             if not data:break  
  29.             connectionSocket.send(data)  
  30.         file.close()  
  31. connectionSocket.close()  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325512068&siteId=291194637