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
Get the file from the server's file system
and send the file content
If the file does not exist, return "404 Not Found" (*)
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
server.py
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
- 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(1024)
- print 'From Server:', receiveSentence
- isEnd = raw_input()
- clientSocket.close()
server.py
- import socket
- import them
- 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 ready to receive'
- while 1:
- connectionSocket, addr = serverSocket.accept()
- sentence = connectionSocket.recv(1024)
- years = ''
- flag = False;
- for ch in sentence:
- if(ch == ' ' and flag ==True):break
- if(flag == True):
- yrs = yrs + 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(1024)
- if not data:break
- connectionSocket.send(data)
- file.close()
- connectionSocket.close()