Sending messages over secure (SSL) WebSockets from Python to Python
up vote
1
down vote
favorite
I have a C++ app, that embeds a Python script.
The C++ app sends cv::Mat
images to the Py script, that in turn runs some image recognition (via a CNN). Basic idea can be found in my gist.
Then my Python script wants to send the results of the CNN-prediction to another app (in Unity I believe) via secure WebSockets with SSL.
I don't have access to the actual Unity app at the moment, so I have to test the actual "sending" part using a simple Python server-app.
I don't have much experience (or knowledge) with sockets and SSL in Python, so I'm hoping for some help.
Everything works if I just use a non-secure HTTP connection, but when I try to introduce HTTPS and SSL, I get problems.
SERVER SIDE:
In the last attempt, I was using the following server script (taken from here):
import asyncio
import pathlib
import ssl
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.load_cert_chain(
pathlib.Path(__file__).with_name('cert.pem'),
pathlib.Path(__file__).with_name('key_wopasswd.pem'))
start_server = websockets.serve(hello, 'localhost', 443, ssl=ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
The certificate and key files were given to me by a colleague, who's in charge of the actual receiving Unity app.
CLIENT SIDE:
After that I tried to connect and send messages either like this (fragment 1):
import json
import http.client, ssl
import time
ws = None
def send(msg="lol"):
global ws
if ws is None:
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.load_cert_chain('cert.pem', 'key_wopasswd.pem')
ws = http.client.HTTPSConnection("localhost", 443, context=ssl_context)
ws.connect()
print("connected successfully!")
else:
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
In which case, simply nothing happens.
Or like this (fragment 2):
import websocket, ssl
import time
ws = None
def send(msg="lol"):
global ws
if ws is None:
ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_REQUIRED,
"ssl_version": ssl.PROTOCOL_TLSv1,
"certfile": "cert.pem",
"keyfile": "key_wopasswd.pem"})
ws.connect("wss://localhost:443")
else:
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
In which case, I get the following error:
Traceback (most recent call last):
File ".client2.py", line 21, in send
ws.connect("wss://localhost:443")
File "C:Program FilesPython36libsite-packageswebsocket_core.py", line 220, in connect
options.pop('socket', None))
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 126, in connect
sock = _ssl_socket(sock, options.sslopt, hostname)
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 253, in _ssl_socket
sock = _wrap_sni_socket(sock, sslopt, hostname, check_hostname)
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 232, in _wrap_sni_socket
server_hostname=hostname,
File "C:Program FilesPython36libssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "C:Program FilesPython36libssl.py", line 808, in __init__
self.do_handshake()
File "C:Program FilesPython36libssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
File "C:Program FilesPython36libssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
I also tried a simple http.server.HTTPServer
, but the only difference was that with the first client (Fragment 1), it did not print the messages after every send, but instead accumulated all the received messages and printed all of them together after I stop the client, with the error: code 400, message Bad request syntax.
tl;dr
Basically, what I need, is a good example of how I can connect to a secure HTTPS server with SSL once, and then continue sending string-messages, until the app stops.
A small update:
It works, if I write the client like this, but only if I close and reopen the connection after every message:
import json
import websocket, ssl
import time
ws = None
def send(msg="..."):
global ws
if ws is None:
ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE,
"ssl_version": ssl.PROTOCOL_TLSv1,
"certfile": "cert.pem",
"keyfile": "key_wopasswd.pem"})
ws.connect("wss://localhost:443")
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
ws.close()
ws = None
########################
i = 0
while i < 10:
i = i + 1
send("i = %d" % i)
python python-3.x ssl websocket
add a comment |
up vote
1
down vote
favorite
I have a C++ app, that embeds a Python script.
The C++ app sends cv::Mat
images to the Py script, that in turn runs some image recognition (via a CNN). Basic idea can be found in my gist.
Then my Python script wants to send the results of the CNN-prediction to another app (in Unity I believe) via secure WebSockets with SSL.
I don't have access to the actual Unity app at the moment, so I have to test the actual "sending" part using a simple Python server-app.
I don't have much experience (or knowledge) with sockets and SSL in Python, so I'm hoping for some help.
Everything works if I just use a non-secure HTTP connection, but when I try to introduce HTTPS and SSL, I get problems.
SERVER SIDE:
In the last attempt, I was using the following server script (taken from here):
import asyncio
import pathlib
import ssl
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.load_cert_chain(
pathlib.Path(__file__).with_name('cert.pem'),
pathlib.Path(__file__).with_name('key_wopasswd.pem'))
start_server = websockets.serve(hello, 'localhost', 443, ssl=ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
The certificate and key files were given to me by a colleague, who's in charge of the actual receiving Unity app.
CLIENT SIDE:
After that I tried to connect and send messages either like this (fragment 1):
import json
import http.client, ssl
import time
ws = None
def send(msg="lol"):
global ws
if ws is None:
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.load_cert_chain('cert.pem', 'key_wopasswd.pem')
ws = http.client.HTTPSConnection("localhost", 443, context=ssl_context)
ws.connect()
print("connected successfully!")
else:
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
In which case, simply nothing happens.
Or like this (fragment 2):
import websocket, ssl
import time
ws = None
def send(msg="lol"):
global ws
if ws is None:
ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_REQUIRED,
"ssl_version": ssl.PROTOCOL_TLSv1,
"certfile": "cert.pem",
"keyfile": "key_wopasswd.pem"})
ws.connect("wss://localhost:443")
else:
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
In which case, I get the following error:
Traceback (most recent call last):
File ".client2.py", line 21, in send
ws.connect("wss://localhost:443")
File "C:Program FilesPython36libsite-packageswebsocket_core.py", line 220, in connect
options.pop('socket', None))
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 126, in connect
sock = _ssl_socket(sock, options.sslopt, hostname)
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 253, in _ssl_socket
sock = _wrap_sni_socket(sock, sslopt, hostname, check_hostname)
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 232, in _wrap_sni_socket
server_hostname=hostname,
File "C:Program FilesPython36libssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "C:Program FilesPython36libssl.py", line 808, in __init__
self.do_handshake()
File "C:Program FilesPython36libssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
File "C:Program FilesPython36libssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
I also tried a simple http.server.HTTPServer
, but the only difference was that with the first client (Fragment 1), it did not print the messages after every send, but instead accumulated all the received messages and printed all of them together after I stop the client, with the error: code 400, message Bad request syntax.
tl;dr
Basically, what I need, is a good example of how I can connect to a secure HTTPS server with SSL once, and then continue sending string-messages, until the app stops.
A small update:
It works, if I write the client like this, but only if I close and reopen the connection after every message:
import json
import websocket, ssl
import time
ws = None
def send(msg="..."):
global ws
if ws is None:
ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE,
"ssl_version": ssl.PROTOCOL_TLSv1,
"certfile": "cert.pem",
"keyfile": "key_wopasswd.pem"})
ws.connect("wss://localhost:443")
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
ws.close()
ws = None
########################
i = 0
while i < 10:
i = i + 1
send("i = %d" % i)
python python-3.x ssl websocket
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
I have a C++ app, that embeds a Python script.
The C++ app sends cv::Mat
images to the Py script, that in turn runs some image recognition (via a CNN). Basic idea can be found in my gist.
Then my Python script wants to send the results of the CNN-prediction to another app (in Unity I believe) via secure WebSockets with SSL.
I don't have access to the actual Unity app at the moment, so I have to test the actual "sending" part using a simple Python server-app.
I don't have much experience (or knowledge) with sockets and SSL in Python, so I'm hoping for some help.
Everything works if I just use a non-secure HTTP connection, but when I try to introduce HTTPS and SSL, I get problems.
SERVER SIDE:
In the last attempt, I was using the following server script (taken from here):
import asyncio
import pathlib
import ssl
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.load_cert_chain(
pathlib.Path(__file__).with_name('cert.pem'),
pathlib.Path(__file__).with_name('key_wopasswd.pem'))
start_server = websockets.serve(hello, 'localhost', 443, ssl=ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
The certificate and key files were given to me by a colleague, who's in charge of the actual receiving Unity app.
CLIENT SIDE:
After that I tried to connect and send messages either like this (fragment 1):
import json
import http.client, ssl
import time
ws = None
def send(msg="lol"):
global ws
if ws is None:
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.load_cert_chain('cert.pem', 'key_wopasswd.pem')
ws = http.client.HTTPSConnection("localhost", 443, context=ssl_context)
ws.connect()
print("connected successfully!")
else:
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
In which case, simply nothing happens.
Or like this (fragment 2):
import websocket, ssl
import time
ws = None
def send(msg="lol"):
global ws
if ws is None:
ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_REQUIRED,
"ssl_version": ssl.PROTOCOL_TLSv1,
"certfile": "cert.pem",
"keyfile": "key_wopasswd.pem"})
ws.connect("wss://localhost:443")
else:
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
In which case, I get the following error:
Traceback (most recent call last):
File ".client2.py", line 21, in send
ws.connect("wss://localhost:443")
File "C:Program FilesPython36libsite-packageswebsocket_core.py", line 220, in connect
options.pop('socket', None))
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 126, in connect
sock = _ssl_socket(sock, options.sslopt, hostname)
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 253, in _ssl_socket
sock = _wrap_sni_socket(sock, sslopt, hostname, check_hostname)
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 232, in _wrap_sni_socket
server_hostname=hostname,
File "C:Program FilesPython36libssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "C:Program FilesPython36libssl.py", line 808, in __init__
self.do_handshake()
File "C:Program FilesPython36libssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
File "C:Program FilesPython36libssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
I also tried a simple http.server.HTTPServer
, but the only difference was that with the first client (Fragment 1), it did not print the messages after every send, but instead accumulated all the received messages and printed all of them together after I stop the client, with the error: code 400, message Bad request syntax.
tl;dr
Basically, what I need, is a good example of how I can connect to a secure HTTPS server with SSL once, and then continue sending string-messages, until the app stops.
A small update:
It works, if I write the client like this, but only if I close and reopen the connection after every message:
import json
import websocket, ssl
import time
ws = None
def send(msg="..."):
global ws
if ws is None:
ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE,
"ssl_version": ssl.PROTOCOL_TLSv1,
"certfile": "cert.pem",
"keyfile": "key_wopasswd.pem"})
ws.connect("wss://localhost:443")
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
ws.close()
ws = None
########################
i = 0
while i < 10:
i = i + 1
send("i = %d" % i)
python python-3.x ssl websocket
I have a C++ app, that embeds a Python script.
The C++ app sends cv::Mat
images to the Py script, that in turn runs some image recognition (via a CNN). Basic idea can be found in my gist.
Then my Python script wants to send the results of the CNN-prediction to another app (in Unity I believe) via secure WebSockets with SSL.
I don't have access to the actual Unity app at the moment, so I have to test the actual "sending" part using a simple Python server-app.
I don't have much experience (or knowledge) with sockets and SSL in Python, so I'm hoping for some help.
Everything works if I just use a non-secure HTTP connection, but when I try to introduce HTTPS and SSL, I get problems.
SERVER SIDE:
In the last attempt, I was using the following server script (taken from here):
import asyncio
import pathlib
import ssl
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.load_cert_chain(
pathlib.Path(__file__).with_name('cert.pem'),
pathlib.Path(__file__).with_name('key_wopasswd.pem'))
start_server = websockets.serve(hello, 'localhost', 443, ssl=ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
The certificate and key files were given to me by a colleague, who's in charge of the actual receiving Unity app.
CLIENT SIDE:
After that I tried to connect and send messages either like this (fragment 1):
import json
import http.client, ssl
import time
ws = None
def send(msg="lol"):
global ws
if ws is None:
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ssl_context.load_cert_chain('cert.pem', 'key_wopasswd.pem')
ws = http.client.HTTPSConnection("localhost", 443, context=ssl_context)
ws.connect()
print("connected successfully!")
else:
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
In which case, simply nothing happens.
Or like this (fragment 2):
import websocket, ssl
import time
ws = None
def send(msg="lol"):
global ws
if ws is None:
ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_REQUIRED,
"ssl_version": ssl.PROTOCOL_TLSv1,
"certfile": "cert.pem",
"keyfile": "key_wopasswd.pem"})
ws.connect("wss://localhost:443")
else:
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
In which case, I get the following error:
Traceback (most recent call last):
File ".client2.py", line 21, in send
ws.connect("wss://localhost:443")
File "C:Program FilesPython36libsite-packageswebsocket_core.py", line 220, in connect
options.pop('socket', None))
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 126, in connect
sock = _ssl_socket(sock, options.sslopt, hostname)
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 253, in _ssl_socket
sock = _wrap_sni_socket(sock, sslopt, hostname, check_hostname)
File "C:Program FilesPython36libsite-packageswebsocket_http.py", line 232, in _wrap_sni_socket
server_hostname=hostname,
File "C:Program FilesPython36libssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "C:Program FilesPython36libssl.py", line 808, in __init__
self.do_handshake()
File "C:Program FilesPython36libssl.py", line 1061, in do_handshake
self._sslobj.do_handshake()
File "C:Program FilesPython36libssl.py", line 683, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)
I also tried a simple http.server.HTTPServer
, but the only difference was that with the first client (Fragment 1), it did not print the messages after every send, but instead accumulated all the received messages and printed all of them together after I stop the client, with the error: code 400, message Bad request syntax.
tl;dr
Basically, what I need, is a good example of how I can connect to a secure HTTPS server with SSL once, and then continue sending string-messages, until the app stops.
A small update:
It works, if I write the client like this, but only if I close and reopen the connection after every message:
import json
import websocket, ssl
import time
ws = None
def send(msg="..."):
global ws
if ws is None:
ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE,
"ssl_version": ssl.PROTOCOL_TLSv1,
"certfile": "cert.pem",
"keyfile": "key_wopasswd.pem"})
ws.connect("wss://localhost:443")
jsonString = json.dumps({"Time":int(time.time()), "Message":msg})
ws.send(jsonString.encode('utf-8'))
ws.close()
ws = None
########################
i = 0
while i < 10:
i = i + 1
send("i = %d" % i)
python python-3.x ssl websocket
python python-3.x ssl websocket
edited yesterday
asked yesterday
Xonxt
15319
15319
add a comment |
add a comment |
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53204281%2fsending-messages-over-secure-ssl-websockets-from-python-to-python%23new-answer', 'question_page');
}
);
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password