首先,使用如下命令生成证书和key:
openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout key.pem
接下来实现服务器:
import socket, ssl,time
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")
bindsocket = socket.socket()
bindsocket.bind(('191.8.1.235', 10023))
bindsocket.listen(5)
def do_something(connstream, data):
#print("data length:",len(data))
return True
def deal_with_client(connstream):
t_recv=0
t_send=0
n = 0
t1=time.clock()
data = connstream.recv(1024)
t2=time.clock()
print("receive time:",t2-t1)
# empty data means the client is finished with us
while data:
if not do_something(connstream, data):
# we'll assume do_something returns False
# when we're finished with client
break
n = n + 1
t1=time.clock()
connstream.send(b'b'*1024)
t2=time.clock()
t_send += t2-t1
print("send time:",t2-t1)
t1=time.clock()
data = connstream.recv(1024)
t2=time.clock()
t_recv +=t2-t1
print("receive time:",t2-t1)
print("avg send time:",t_send/n,"avg receive time:",t_recv/n)
# finished with client
while True:
newsocket, fromaddr = bindsocket.accept()
connstream = context.wrap_socket(newsocket, server_side=True)
try:
deal_with_client(connstream)
finally:
connstream.shutdown(socket.SHUT_RDWR)
connstream.close()
客户端:
import socket, ssl, pprint,time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# require a certificate from the server
ssl_sock = ssl.wrap_socket(s,
ca_certs="cert.pem",
cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('191.8.1.235', 10023))
pprint.pprint(ssl_sock.getpeercert())
# note that closing the SSLSocket will also close the underlying socket
n=0
t_send=0
t_recv=0
while n <1000:
n = n+1
t1=time.clock()
ssl_sock.send(b'a'*100)
t2=time.clock()
t_send += t2-t1
print("send time:",t2-t1)
t1=time.clock()
data=ssl_sock.recv(1024)
t2=time.clock()
t_recv += t2-t1
print("receive time:",t2-t1)
#print(len(data))
print("avg send time:",t_send/n,"avg receive time:",t_recv/n)
#ssl_sock.send(b'')
ssl_sock.close()