【发布时间】:2018-04-10 09:04:26
【问题描述】:
我正在使用:https://pypi.python.org/pypi/websocket-client
尝试将 python 2.7 websockets 客户端连接到实际使用 https 而不是 ws 或 wss 的 URL,但我收到以下错误。无论如何我可以解决这个问题吗?请注意,我没有创建这个 websockets 服务器,所以我无法控制它是否符合 ws 或 wss 标准。
错误:
方案 https 无效
关闭
Python 代码如下:
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()
我知道我可以连接到这个 websocket URL,因为下面的 javascript 代码有效。
Javascript 代码如下:
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)
});
}
我尝试修改 websocket-client 的源代码。去 /Python/2.7/site-packages/websocket/_url.py 的 websocket-client 的代码并修改以下代码:
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)
但是现在当我运行它时,我得到另一个错误
[Errno 49] 无法分配请求的地址
关闭
【问题讨论】:
-
安全 websocket 的架构是
wss:而不是https:。 -
@KlausD。我了解,但是创建此 websocket 服务器的人使用了 https。所以我实际上想通过 https 连接。
-
没有什么能比得上通过 HTTPS 的 websocket。使用
wss:。这是一个带有 SSL/TLS 的 websocket。 -
使用 ws 或 wss 不适用于此服务器(我没有制作服务器)。看看我的节点 js 代码,信不信由你在节点 js 中它适用于 https 而不是 ws 或 wss。我必须有一种方法可以在 python 中做到这一点。
-
@toma 谢谢,但我放弃了 python,只是将一个 node.js 组件集成到我的 python 代码中(效果很好)。服务器代码(不是我写的)是问题所在,我无法真正改变它。我决定不继续战斗了。
标签: javascript python websocket