Server:
Create a connection socket when a customer contacts receive an HTTP request (*) from this connection to interpret the specific file requested by the request
Get the file from the server's file system and send the file contents if the file does not exist, then return "404 Not Found" (*)
Client:
Client can establish a TCP connection with the server
Client requests a file on the server side over a TCP connection
Display the contents of the file presented to the client
Note: Before running this file, the server.py directory needs to contain the file folder, which contains the files in the server, the client can request files from the server file.
Readme: First Open the server.py, turn on the server
Then open client.py, enter the file name, including the suffix
The server filesystem is the file folder
Specific information about the file that appears in the client.py command-line window
Press any key to close the client
client.py
[Python]View PlainCopy
- Import socket
- ServerName = ' 127.0.0.1 '
- ServerPort = 50008
- Clientsocket = Socket.socket (socket.af_inet,socket. SOCK_STREAM)
- Clientsocket.connect ((Servername,serverport))
- Print ' Input the HTTP request: '
- sentence = ' '
- While True:
- TMP = Raw_input ()
- Sentence = sentence + tmp
- if (tmp=="): break
- Clientsocket.send (sentence)
- Receivesentence = Clientsocket.recv (1024x768)
- Print ' from Server: ', receivesentence
- Isend = Raw_input ()
- Clientsocket.close ()
server.py
[Python]View PlainCopy
- Import socket
- Import OS
- ServerPort = 50008
- ServerSocket = Socket.socket (socket.af_inet,socket. SOCK_STREAM)
- Serversocket.bind ((' 127.0.0.1 ', serverport))
- Serversocket.listen (1)
- print ' The server is a ready to receive '
- While 1:
- Connectionsocket, addr = Serversocket.accept ()
- Sentence = Connectionsocket.recv (1024x768)
- Ans = "
- flag = False;
- For ch in sentence:
- if (ch = = "and flag = =True) : break
- if (flag = = True):
- ans = ans + ch;
- elif (ch=="):
- flag = True;
- Path = ' file//' + ans
- if (os.path.exists (path) = =False):
- Connectionsocket.send (' 404 Not Found ')
- Else:
- File = open (path,' R ')
- while 1:
- data = File.read (1024x768)
- if not data: break
- Connectionsocket.send (data)
- File.close ()
- Connectionsocket.close ()
Python a simple Web server and client