Posted on

The Error

Traceback (most recent call last):
  File "/Users/fenghexu/OneDrive - zju.edu.cn/Documents/ZJU/Courses/2019 Fall & Winter/blogdiy/demo/auto_deploy_docker/web_socket.py", line 37, in <module>
    ssl_context.load_cert_chain(localhost_pem)
ssl.SSLError: [SSL] PEM lib (_ssl.c:3824)

Python Secure Web Socket Source Code

That’s where the localhost.pem required.

import asyncio
import json
import logging
import websockets
import ssl
import pathlib

logging.basicConfig()

USERS = set()


async def register(websocket):
    USERS.add(websocket)
    # await notify_users()


async def unregister(websocket):
    USERS.remove(websocket)


async def deploy_service(websocket, path):
    await register(websocket)
    try:
        # await websocket.send()
        async for message in websocket:
            data = json.loads(message)
            print(data)
            await websocket.send('data received')

    finally:
        await unregister(websocket)


ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
localhost_pem = pathlib.Path(__file__).with_name("localhost.pem")
ssl_context.load_cert_chain(localhost_pem)

start_server = websockets.serve(deploy_service, '0.0.0.0', 6789, ssl=ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Solution

I changed the way that I generate the localhost.pem file

Original

$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout key.pem -out cert.pem
$ cp key.pem localhost.pem

Current

$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout localhost.pem -out localhost.pem

Now the 2 files are combined together.

The solution to a Real Application

But this does not work when I try to connect to wss server from a https webpage client. In this case, the solution is to use a certbot, as I have illustrated here:

References

  1. https://github.com/jupyter/notebook/issues/507

Leave a Reply

Your email address will not be published. Required fields are marked *