# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import socket
import ssl
from struct import pack, unpack

HOST = 'localhost'
PORT = 12345
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
#ctx.options |= ssl.PROTOCOL_TLSv1_2
#ctx.options |= ssl.OP_NO_SSLv2
#ctx.options |= ssl.OP_NO_SSLv3
#ctx.options |= ssl.OP_NO_TLSv1
#ctx.options |= ssl.OP_NO_TLSv1_1
#ctx.options |= ssl.OP_NO_TLSv1_3
sraw = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sraw.connect((HOST, PORT))
s = ctx.wrap_socket(sraw, server_hostname=HOST)
print('connected')
print('server is %s' % (s.getpeercert())) # empty with CERT_NONE - should work with CERT_REQUIRED, but that does not work with self signed
a = 123
b = 456
s.sendall(pack('>ii', a, b))
c = unpack('>i', s.recv(4))
print('%d' % (c))
v = 'ABC'
vb = bytes(v, 'UTF-8')
s.sendall(pack('b' + str(len(vb)) + 's', len(vb), vb))
v2len = unpack('b', s.recv(1))[0]
v2 = str(s.recv(v2len), 'UTF-8')
print(v2)
s.close()
