python创建socket对象_python如何使用socket来传输对象
发布日期:2021-09-13 06:38:55 浏览次数:7 分类:技术文章

本文共 2109 字,大约阅读时间需要 7 分钟。

2016-08-09 回答

现在记录https服务端的编写。

import ssl, socket, time

if __name__ == "__main__":

context = ssl.sslcontext(ssl.protocol_sslv23)

#context.load_cert_chain(certfile=‘key_pub.pem’, keyfile=‘key_priv.pem')   #可以分开定义公钥和私钥文件,也可以合并成一个文件

context.load_cert_chain(certfile=’cert.pem')

bindsocket = socket.socket()

bindsocket.bind(('127.0.0.1', 443))

bindsocket.listen(5)

newsocket, fromaddr = bindsocket.accept()

connstream = context.wrap_socket(newsocket, server_side=true)

try:

data = connstream.recv(1024)

print(data)

buf = 'hi nn%f\n\n\n\n'%time.time()

buf = buf.encode()

connstream.send(buf)

finally:

connstream.shutdown(socket.shut_rdwr)

connstream.close()

bindsocket.close()

此例没有使用socketserver框架,目的在于测试ssl模块的用法。

继续,用框架实现https服务

import socketserver, ssl, time

class myhttpshandler_socket(socketserver.baserequesthandler):

def handle(self):

context = ssl.sslcontext(ssl.protocol_sslv23)

context.load_cert_chain(certfile="cert.pem")

sslsocket = context.wrap_socket(self.request, server_side=true)

self.data = sslsocket.recv(1024)

print(self.data)

buf = 'test https server handler

%f'%time.time()

buf = buf.encode()

sslsocket.send(buf)

if __name__ == "__main__":

port = 443

httpd = socketserver.tcpserver(('localhost‘, port), myhttpshandler_socket)

print(’https serving at port', port)

httpd.serve_forever()

说明:handle()函数负责所有与客户端的通信。客户端连接过来之后,ssl模块载入证书,并用sslsocket对socket进行封装,屏蔽底层的加密通信细节。

下面再给出https文件服务器代码,文件访问功能由simplehttprequesthandler实现,数据加密传输由ssl实现。

import socketserver, ssl, time, http.server

class myhttps_simplehttprequesthandler(http.server.simplehttprequesthandler):

def setup(self):

print('setup')

context = ssl.sslcontext(ssl.protocol_sslv23)

context.load_cert_chain(certfile=‘cert.pem’)

sslsocket = context.wrap_socket(self.request, server_side=true)

self.rfile = sslsocket.makefile('rb', self.rbufsize)

self.wfile = sslsocket.makefile('wb', self.wbufsize)

if __name__ == "__main__":

port = 443

httpd = socketserver.tcpserver(("localhost", port), myhttps_simplehttprequesthandler)

print('https serving at port', port)

httpd.serve_forever()

最后,要指出的是setup()和handle()都是在客户端开始连接之后才被调用,从顺序上来说setup()先于handle()。

转载地址:https://blog.csdn.net/weixin_39767645/article/details/110981824 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python pytz下载_python:pytz包安装问题:ImportError:没有名为pytz的模块
下一篇:python import同一目录的其他文件_Python文件和目录操作示例

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月04日 21时10分29秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章