1#-*- coding: utf-8 -*-2#
@time : 2019-07-17 1:393#
@file : 網路socket實現http伺服器.py4#
@software: pycharm56
import
socket
7importre8
910defserver_conn(conn,file_name):11#
1.響應頭部
12if file_name == '
/index.html':
13#可換成html本地檔案
#2.響應body
16 response += "
\r\n
"17 response += ""18
#3.傳送請求
#2.響應body
23 response += "
\r\n
"24 response += ""25
#3.傳送請求
26 conn.sendall(bytes(response, encoding="
utf-8"))
27pass
2829
30def
main(host, port):31#
1.建立套接字
32 server =socket.socket(socket.af_inet,socket.sock_stream)
33 server.setsockopt(socket.sol_socket,socket.so_reuseaddr,1)34#
2.繫結
35server.bind((host, port))36#
3.監聽
37 server.listen(128)38#
4.連線
39while
true:
40 conn, address =server.accept()41#
接收客戶端訊息,最大位元組數1024
42 client_mess = conn.recv(1024)43#
接收瀏覽器返回資料
44 client_content = str(client_mess, encoding="
utf-8
").splitlines()45#
切割匹配訪問路徑
46 file_name = re.match(r"
[^/]+(/[^ ]*)
",client_content[0])
47if
file_name:
48 file_name1 = file_name.group(1)
49if file_name1 == "/"
:50 file_name1 = "
/index.html"51
(file_name1)52#
print(client_content)
53server_conn(conn,file_name1)
54conn.close()
55pass
5657
58if
__name__ == "
__main__":
59 main("
127.0.0.1
", 7890)
6061
#注 : http協議,三次握手,四次揮手
使用socket實現簡單地http伺服器
本文使用ubuntu虛擬機器作為伺服器端 任意瀏覽器作為訪問瀏覽器 標識響應瀏覽器,不會再瀏覽器中顯示 response r n 換行 response hello,world 瀏覽器中輸出的結果 new socket.send response.encode utf 8 new socket.cl...
symbian中socket實現HTTP流程
用socket類來實現http協議,socket是用tcp的協議。本文用到了4個活動物件。1.rconnection開啟網路通道 2.socketengine 3.socketread 4.socketwrite 操作的流程如下 1.先開啟網路通道類。獲取乙個資訊通道,例如 gprs wlen 2....
python socket簡單實現SSH伺服器端
server import socket,os server socket.socket server.bind localhost 9999 server.listen while true conn,addr server.accept while true data conn.recv 102...