服务器:
从服务器的文件系统获取该文件
客户端:
客户端可以与服务器建立TCP连接
客户端通过TCP连接请求服务器端的某一文件
在客户端显示介绍到的文件内容
注:在运行此文件前,server.py目录下需要包含file文件夹,里面装有服务器里的文件,客户端可以向服务器请求file里的文件。
readme:首先打开server.py,开启服务器
然后打开client.py,输入文件名,包括后缀
服务器文件系统为file文件夹
client.py的命令行窗口中出现文件的具体信息
按任意键关闭客户端
client.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 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 ready to receive'
- while 1:
- connectionSocket, addr = serverSocket.accept()
- sentence = connectionSocket.recv(1024)
- 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(1024)
- if not data:break
- connectionSocket.send(data)
- file.close()
- connectionSocket.close()