Nik*_*s R 7 html python sockets client
我已经设置了一个小脚本,应该用html为客户端提供支持.
import socket
sock = socket.socket()
sock.bind(('', 8080))
sock.listen(5)
client, adress = sock.accept()
print "Incoming:", adress
print client.recv(1024)
print
client.send("Content-Type: text/html\n\n")
client.send('<html><body></body></html>')
print "Answering ..."
print "Finished."
import os
os.system("pause")
Run Code Online (Sandbox Code Playgroud)
但它在浏览器中显示为纯文本.你能说出我需要做什么吗?我只是在谷歌找不到帮助我的东西..
谢谢.
Ray*_*ger 15
响应头应包含指示成功的响应代码.在Content-Type行之前,添加:
client.send('HTTP/1.0 200 OK\r\n')
Run Code Online (Sandbox Code Playgroud)
另外,为了使测试更加明显,请在页面中添加一些内容:
client.send('<html><body><h1>Hello World</body></html>')
Run Code Online (Sandbox Code Playgroud)
发送响应后,关闭连接:
client.close()
Run Code Online (Sandbox Code Playgroud)
和
sock.close()
Run Code Online (Sandbox Code Playgroud)
正如其他海报所指出的那样,用\r\n而不是终止每一行\n.
那些新增的,我能够成功运行测试.在浏览器中,我进入了localhost:8080.
这是所有代码:
import socket
sock = socket.socket()
sock.bind(('', 8080))
sock.listen(5)
client, adress = sock.accept()
print "Incoming:", adress
print client.recv(1024)
print
client.send('HTTP/1.0 200 OK\r\n')
client.send("Content-Type: text/html\r\n\r\n")
client.send('<html><body><h1>Hello World</body></html>')
client.close()
print "Answering ..."
print "Finished."
sock.close()
Run Code Online (Sandbox Code Playgroud)