Tasos
Tasos

Reputation: 1637

Python websocket create connection

I have this server

https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/echo_tls/server.py

And I want to connect to the server with this code:

ws = create_connection("wss://127.0.0.1:9000")

What options do I need to add to create_connection? Adding sslopt={"cert_reqs": ssl.CERT_NONE} does not work:

websocket._exceptions.WebSocketBadStatusException: Handshake status 400

Upvotes: 1

Views: 18835

Answers (2)

Tasos
Tasos

Reputation: 1637

This works

import asyncio
import websockets
import ssl

async def hello():
    async with websockets.connect('wss://127.0.0.1:9000',ssl=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)) as websocket:
        data = 'hi'
        await websocket.send(data)
        print("> {}".format(data))

        response = await websocket.recv()
        print("< {}".format(response))

asyncio.get_event_loop().run_until_complete(hello())

Upvotes: 6

karelv
karelv

Reputation: 814

For me the option from the question seems to work:

from websocket import create_connection
import ssl

ws = create_connection("wss://echo.websocket.org", sslopt={"cert_reqs": ssl.CERT_NONE})

ws.send("python hello!")
print (ws.recv())
ws.close()

See also here: https://github.com/websocket-client/websocket-client#faq

Note: I'm using win7 with python 3.6.5 with following packages installed(pip):

  • simple-websocket-server==0.4.0
  • websocket-client==0.53.0
  • websockets==6.0

Upvotes: 1

Related Questions