gpt4 book ai didi

javascript - 无法与 websocket 通信。高速公路 : received HELLO message, 且 session 尚未建立

转载 作者:行者123 更新时间:2023-11-30 00:34:44 28 4
gpt4 key购买 nike

我正在尝试使用 Python 3.4、Django、Autobahn 和 JS 构建 WebSocket session 。我已经在 python 端成功运行了 websocket 服务器,但是我无法订阅或接收服务器发布的任何数据

我的代码相当简单:

class TestAppWS(ApplicationSession):
"""
An application component that publishes an event every second.
"""
def onConnect(self):
self.join(u"realm1")

@asyncio.coroutine
def onJoin(self, details):
counter = 0
while True:
self.publish('com.myapp.topic1', counter)
counter += 1
yield from asyncio.sleep(1)


def start_ws():
print("Running")
session_factory = ApplicationSessionFactory()
session_factory.session = TestAppWS
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

# factory = WebSocketServerFactory("ws://localhost:8090", debug=False)
# factory.protocol = MyServerProtocol

server = None
try:
transport_factory = WampWebSocketServerFactory(session_factory, debug_wamp=True)
loop = asyncio.get_event_loop()
coro = loop.create_server(transport_factory, 'localhost', 8090)
server = loop.run_until_complete(coro)
loop.run_forever()
except OSError:
print("WS server already running")
except KeyboardInterrupt:
pass
finally:
if server:
server.close()
loop.close()

start_ws() 在单独的 Thread 对象中运行。如果我在浏览器上访问 localhost:8090,我可以看到 Autobahn 欢迎消息。

在前端我有

var connection = new autobahn.Connection({
url: 'ws://localhost:8090/',
realm: 'realm1'}
);
connection.onopen = function (session) {
var received = 0;

function onevent1(args) {
console.log("Got event:", args[0]);
received += 1;
if (received > 5) {
console.log("Closing ..");
connection.close();
}
}

session.subscribe('com.myapp.topic1', onevent1);
};

connection.open();

它似乎不起作用,当我尝试连接前端时,我在后端收到以下错误:

Failing WAMP-over-WebSocket transport: code = 1002, reason = 'WAMP Protocol Error (Received <class 'autobahn.wamp.message.Hello'> message, and session is not yet established)'
WAMP-over-WebSocket transport lost: wasClean = False, code = 1006, reason = 'connection was closed uncleanly (I failed the WebSocket connection by dropping the TCP connection)'
TX WAMP HELLO Message (realm = realm1, roles = [<autobahn.wamp.role.RolePublisherFeatures object at 0x04710270>, <autobahn.wamp.role.RoleSubscriberFeatures object at 0x047102B0>, <autobahn.wamp.role.RoleCallerFeatures object at 0x047102D0>, <autobahn.wamp.role.RoleCalleeFeatures object at 0x047102F0>], authmethods = None, authid = None)
RX WAMP HELLO Message (realm = realm1, roles = [<autobahn.wamp.role.RoleSubscriberFeatures object at 0x04710350>, <autobahn.wamp.role.RoleCallerFeatures object at 0x04710330>, <autobahn.wamp.role.RoleCalleeFeatures object at 0x04710390>, <autobahn.wamp.role.RolePublisherFeatures object at 0x04710370>], authmethods = None, authid = None)
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\autobahn\wamp\websocket.py", line 91, in onMessage
self._session.onMessage(msg)
File "C:\Python34\lib\site-packages\autobahn\wamp\protocol.py", line 429, in onMessage
raise ProtocolError("Received {0} message, and session is not yet established".format(msg.__class__))
autobahn.wamp.exception.ProtocolError: Received <class 'autobahn.wamp.message.Hello'> message, and session is not yet established

在 javascript 控制台上我看到:

Uncaught InvalidAccessError: Failed to execute 'close' on 'WebSocket': The code must be either 1000, or between 3000 and 4999. 1002 is neither.

有什么想法吗?看起来 session 没有开始,老实说,不清楚这个 session 是如何工作的。一旦建立了来自客户端的连接,是否应该初始化 session ?

最佳答案

您的TestAppWs 和您的浏览器代码都是WAMP 应用程序组件。这两个都需要连接到 WAMP 路由器。然后他们可以自由地相互交谈(就好像中间没有路由器一样……透明地)。

运行方法如下。

运行 WAMP 路由器。

使用 Crossbar.io (但您也可以使用 other WAMP routers),这很简单。首先安装 Crossbar.io:

pip install crossbar

Crossbar.io (currently) runs on Python 2, but that's irrelevant as your app components can run on Python 3 or any other WAMP supported language/run-time. Think of Crossbar.io like a black-box, an external infrastructure, like a database system.

然后创建并启动一个 Crossbar.io 默认路由器:

cd $HOME
mkdir mynode
cd mynode
crossbar init
crossbar start

运行您的 Python 3/asyncio 组件

import asyncio
from autobahn.asyncio.wamp import ApplicationSession


class MyComponent(ApplicationSession):

@asyncio.coroutine
def onJoin(self, details):
print("session ready")

counter = 0
while True:
self.publish('com.myapp.topic1', counter)
counter += 1
yield from asyncio.sleep(1)


if __name__ == '__main__':
from autobahn.asyncio.wamp import ApplicationRunner

runner = ApplicationRunner(url = "ws://localhost:8080/ws", realm = "realm1")
runner.run(MyComponent)

运行浏览器组件

var connection = new autobahn.Connection({
url: 'ws://localhost:8080/ws',
realm: 'realm1'}
);

connection.onopen = function (session) {
var received = 0;

function onevent1(args) {
console.log("Got event:", args[0]);
received += 1;
if (received > 5) {
console.log("Closing ..");
connection.close();
}
}

session.subscribe('com.myapp.topic1', onevent1);
};

connection.open();

关于javascript - 无法与 websocket 通信。高速公路 : received HELLO message, 且 session 尚未建立,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27720020/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com