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)









share|improve this question




























    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)









    share|improve this question


























      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)









      share|improve this question















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 8 at 11:07

























      asked Nov 8 at 8:53









      Xonxt

      15319




      15319





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          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





































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          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




















































































          Popular posts from this blog

          Schultheiß

          Verwaltungsgliederung Dänemarks

          Liste der Kulturdenkmale in Wilsdruff