首页 > 解决方案 > Invalid response when I use my socket code

问题描述

I have a socket test file, and running:

import socket

sock = socket.socket()

sock.bind(('127.0.0.1', 8080))
sock.listen(5)


while True:
    conn, addr = sock.accept()
    data = conn.recv(8096)
    print(data)
    conn.send(b'123456')
    conn.close()

when I use browser request the 127.0.0.1:8080, but in my browser there only get invalid response error:

enter image description here

标签: pythonsocketshttp

解决方案


没有响应头,你应该添加响应头:

conn.send(b'HTTP/1.1 200 OK\r\n\r\n')  
conn.send(b'123456')

推荐阅读