python一個簡單的web伺服器和用戶端

來源:互聯網
上載者:User

標籤: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 
  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 os  
  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.     ans = ‘‘  
  13.     flag = False;  
  14.     for ch in sentence:  
  15.         if(ch == ‘ ‘ and flag ==True):break  
  16.         if(flag == True):  
  17.             ans = ans + 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()  

python一個簡單的web伺服器和用戶端

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.