用socket发送信息在浏览器上显示出来

服务端代码:

import socket

def main():
    sock=socket.socket()
    sock.bind(('localhost',8089))
    sock.listen(5)
    while True:
        connection,address=sock.accept()
        buf=connection.recv(1024)
        print(buf.decode('utf8'))
        # http协议头是文本形式, 以\r\n作为每个字段的分隔, 最后头部以\r\n结束, 所以我们主要构造好 http头, 浏览器就能识别的, 接下来的正文, 就能按照html的标准的编写了
        connection.sendall(bytes("HTTP/1.1 201 OK\r\n\r\n", 'utf8'))
        connection.sendall(bytes("<h1 style='color:red'>NBA</h1>",'utf8'))
        # with open("hellow.html",'rb') as  f:
        #   data=f.read()

        connection.close()


if __name__=="__main__":
    main()

 

然后在浏览器发送信息,效果如图:

最好是在谷歌浏览器下运行,运行一直失败或者浏览器端显示链接失败,127.0.0.1 发送的响应无效。原因是可能被防火墙拦截了,尝试关掉下。如果都没问题,那主要是因为有段代码要写

connection.sendall(bytes("HTTP/1.1 201 OK\r\n\r\n", 'utf8')),这是以http协议头是文本形式,构造好 http头, 浏览器就能识别。没有的话,有的浏览器会报错,接收不到服务端发送来的数据

 

posted @ 2018-07-05 11:10  小L小  阅读(862)  评论(0编辑  收藏  举报