標籤:zju lis stream 開啟 The .net 圖片 == 包含
伺服器:
當客戶聯絡時建立一個串連通訊端 從這個串連接收HTTP請求(*) 解釋該請求所請求的特定檔案
從伺服器的檔案系統擷取該檔案 並傳送檔案內容 如果檔案不存在,則返回“404 Not Found”(*)
用戶端:
用戶端可以與伺服器建立TCP串連
用戶端通過TCP串連請求伺服器端的某一檔案
在用戶端顯示介紹到的檔案內容
註:在運行此檔案前,server.py目錄下需要包含file檔案夾,裡面裝有伺服器裡的檔案,用戶端可以向伺服器請求file裡的檔案。
readme:首先開啟server.py,開啟伺服器
然後開啟client.py,輸入檔案名稱,包括尾碼
伺服器檔案系統為file檔案夾
client.py的命令列視窗中出現檔案的具體資訊
按任意鍵關閉用戶端
client.py
[python] view plain copy
- 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
[python] view plain copy
- 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()
python一個簡單的web伺服器和用戶端