基于SOCKET写一个web应用

py文件

import socket

def server_run():
    soc = socket.socket()
    soc.bind(('127.0.0.1', 8008))
    soc.listen(5)
    while True:
        conn, addr = soc.accept()
        recv_data = conn.recv(1024)
        print(recv_data)
        # 1 直接在send里写,发送给客户端
        # conn.send(b'HTTP/1.1 200 OK\r\n\r\n

hello web

') #2 打开一个html文件,发送给客户端 # with open('index.html','r',encoding='utf-8') as f: # data=f.read() # conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8')) # 3 动态网页,字符串替换 import time now=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(now) with open('index.html','r',encoding='utf-8') as f: data=f.read() data=data.replace('@@@',now) conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8')) conn.close() if __name__ == '__main__': server_run()

index.html 文件




    
    Title


@@@

你可能感兴趣的:(基于SOCKET写一个web应用)