Python套接字服务器处理HTTPS请求 [英] Python socket server handle HTTPS request

查看:209
本文介绍了Python套接字服务器处理HTTPS请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python 2.7和socket模块编写了一个套接字服务器.

I wrote a socket server using Python 2.7 and the socket module.

当我发出HTTP请求时,一切都按预期工作:服务器接受该请求并正确回答.但是,如果不是(例如)http://a.com,而是浏览https://a.com,我会收到某种加密的标头,并且我不知道如何告诉客户端服务器不支持HTTPS.

Everything works as expected when I issue an HTTP request: the server accepts it and answers correctly. But if instead of (let's say) http://a.com I browse for https://a.com I receive some kind of encrypted header and I don't know how to tell the client that HTTPS is not supported by the server.

我在Google上搜索了一下,但没有任何好处.我尝试用简单的HTTP进行回复,但浏览器显然忽略了该响应.

I googled a bit but nothing good. I tried to reply in plain HTTP but the response is clearly ignored by the browser.

如果有人能够向我展示一种告诉客户端没有SSL的方法,那将对我有真正的帮助.

If anyone would be able to show me a way to tell the client there's no SSL it would really help me.

谢谢.

推荐答案

我遇到了同样的问题.您必须这样在代码中配置"ssl"上下文:

I had the same problem. You have to configure "ssl" context within your code as such:

import socket, ssl

HOST = "www.youtube.com"
PORT = 443

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_sock = context.wrap_socket(s, server_hostname=HOST)
s_sock.connect((HOST, 443))
s_sock.send(" GET / HTTP/1.1\r\nHost: www.youtube.com\r\n\r\n ".encode())

while True:
    data = s_sock.recv(2048)
    if ( len(data) < 1 ) :
        break
    print(data)

s_sock.close()

这篇关于Python套接字服务器处理HTTPS请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆