0

I'm using: https://pypi.python.org/pypi/websocket-client

Trying to connect a python 2.7 websockets client to a URL which actually uses https and not ws or wss, but i'm getting the following error. Anyway I can get around this? Please note that I did not create this websockets server so I have no control over making it conform to ws or wss standards.

Error:

scheme https is invalid

closed

Python code is below:

import websocket
import thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("https://MYURL",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

I know that I can connect to this websocket URL because the following javascript code works.

Javascript code is below:

const io = require('socket.io-client');

var socket = io.connect('https://MYURL', { transports: ['websocket'] });
socket.on('connect', () => {
  console.log('socket connected');
  getMarket();
});

socket.on('disconnect', () => {
  console.log('socket disconnected');
});

getMarket = () => {
  socket.emit('getMarket', {});

  socket.once('market', (market) => {
    console.log("stuff", market)
  });
}

I tried modifying the source code for websocket-client. Went to websocket-client's code at /Python/2.7/site-packages/websocket/_url.py and modified the following code:

is_secure = False
if scheme == "ws":
    if not port:
        port = 80
elif scheme == "wss":
    is_secure = True
    if not port:
        port = 443
else:
    pass
    #raise ValueError("!scheme %s is invalid" % scheme)

But now when I run it, I get another error

[Errno 49] Can't assign requested address

closed

LampShade
  • 2,675
  • 5
  • 30
  • 60
  • 3
    The schema for secure websockets is `wss:` not `https:`. – Klaus D. Oct 29 '17 at 07:42
  • @KlausD. I understand, but the person who created this websocket server used https. So I actually want to connect via https. – LampShade Oct 29 '17 at 14:46
  • 2
    There is nothing like a websocket via HTTPS. Use `wss:`. Which is a websocket with SSL/TLS. – Klaus D. Oct 29 '17 at 14:50
  • Using ws or wss doesn’t work with this server(I didn’t make the server). Look at my node js code, believe it or not in node js it works with https and not ws or wss. There has to be a way I can do that in python. – LampShade Oct 29 '17 at 15:21
  • @LampShade did you trie to assign `port = 433` instead of just `pass`? – toma Jan 20 '18 at 19:35
  • 1
    @toma Thanks but I gave up on the python and just integrated a node.js component into my python code (which works fine). The server code (not written by me) is the problem and I cannot really change it. I decided to not continue the battle. – LampShade Jan 21 '18 at 20:07

1 Answers1

-1

I also got into the same situation and posted a question here

Without any answer, I tried to follow your step by editing _url.py and it works for me. Here is my attempt in editing the _url.py:

def parse_url(url):
    """
    parse url and the result is tuple of
    (hostname, port, resource path and the flag of secure mode)

    url: url string.
    """
    if ":" not in url:
        raise ValueError("url is invalid")

    scheme, url = url.split(":", 1)

    parsed = urlparse(url, scheme="ws")
    if parsed.hostname:
        hostname = parsed.hostname
    else:
        raise ValueError("hostname is invalid")
    port = 0
    if parsed.port:
        port = parsed.port

    is_secure = False
    if scheme == "ws":
        if not port:
            port = 80
    elif scheme == "wss":
        is_secure = True
        if not port:
            port = 443
    else:
        if scheme == "https":
            is_secure = True
            if not port:
                port = 443
        else:
            raise ValueError("scheme %s is invalid" % scheme)

    if parsed.path:
        resource = parsed.path
    else:
        resource = "/"

    if parsed.query:
        resource += "?" + parsed.query

    return hostname, port, resource, is_secure
Huynh
  • 392
  • 5
  • 16