How to fix Python WebSocket ValueError: scheme http is invalid
Problem:
You want to use Python to connect to your WebSocket server:
import websocket
ws = websocket.WebSocket()
ws.connect("http://192.168.1.211/ws")
But you see an error message like
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-5108525d0b43> in <module>
1 import websocket
2 ws = websocket.WebSocket()
----> 3 ws.connect("http://10.228.152.103/ws")
4 while True:
5 result = ws.recv()
c:\python38\lib\site-packages\websocket_core.py in connect(self, url, **options)
220 # FIXME: "header", "cookie", "origin" and "host" too
221 self.sock_opt.timeout = options.get('timeout', self.sock_opt.timeout)
--> 222 self.sock, addrs = connect(url, self.sock_opt, proxy_info(**options),
223 options.pop('socket', None))
224
c:\python38\lib\site-packages\websocket_http.py in connect(url, options, proxy, socket)
106 return _open_proxied_socket(url, options, proxy)
107
--> 108 hostname, port, resource, is_secure = parse_url(url)
109
110 if socket:
c:\python38\lib\site-packages\websocket_url.py in parse_url(url)
61 port = 443
62 else:
---> 63 raise ValueError("scheme %s is invalid" % scheme)
64
65 if parsed.path:
ValueError: scheme http is invalid
Solution
The websocket-client
library wants you to useĀ ws://host/path
instead of http://host/path
. So instead of
ws.connect("http://10.228.152.103/ws")
use
ws.connect("http://10.228.152.103/ws")