Websocket 客户端在收到来自服务器的消息时未调用 on_message_callback() 函数
Websocket client is not calling on_message_callback() function when it receives a message from server
我想让服务器和客户端相互通信。
客户端:
@gen.coroutine
def connect(self):
print("trying to connect")
try:
self.ws = yield websocket_connect(self.url, connect_timeout=99999, on_message_callback=on_message)
except Exception as e:
print("connection error : {}".format(e))
print("connected")
但是这里没有调用on_message 每当它的服务器发送消息时。你知道这些吗?
嗯,我看了一下源码。我无法查明问题,因为我没有
了解它的大部分在做什么。
但我注意到某些我认为可能导致问题的事情。为了
示例 this code block:
response = yield self.ws.read_message(callback=self.cb_receive_weight)
...
if response.done() :
这会引发错误。 response
不是未来,而是实际的 websocket
消息字符串。因此,它会引发一个 AttributeError,它没有 done()
方法。
其次,callback=self.cb_receive_weight
这将调用cd_receive_weight
带有未来的方法,而不是消息。所以,那是行不通的。
我认为事情没有按预期工作可能是因为你在混合 yield
和回调。
记住,yield object
会自动调用 object.result()
。考虑:
response = yield self.ws.read_message()
以上,ws.read_message()
returns一个Future,但是yield
,会等到Future
有一个结果。当 Future 得到解析时,yield
将调用它的 result()
方法。
response
将等于该结果。
如果您正在使用 yield
,则您实际上并不需要使用回调。我建议不要
完全使用回调编码风格。避免使用它们并使用协程 (yield
)
在可能的情况下。
代码会更短,更有条理。
示例:
@gen.coroutine
def connect(self):
self.ws = yield websocket_connect(url)
self.run()
...
@gen.coroutine
def get_weight_from_global_network(self):
while True:
response = yield self.ws.read_message()
# do something with the response
self.cb_recieve_weight(weight=response)
虽然,我不能说这是否能解决您的问题。
我想让服务器和客户端相互通信。
客户端:
@gen.coroutine
def connect(self):
print("trying to connect")
try:
self.ws = yield websocket_connect(self.url, connect_timeout=99999, on_message_callback=on_message)
except Exception as e:
print("connection error : {}".format(e))
print("connected")
但是这里没有调用on_message 每当它的服务器发送消息时。你知道这些吗?
嗯,我看了一下源码。我无法查明问题,因为我没有 了解它的大部分在做什么。
但我注意到某些我认为可能导致问题的事情。为了 示例 this code block:
response = yield self.ws.read_message(callback=self.cb_receive_weight)
...
if response.done() :
这会引发错误。 response
不是未来,而是实际的 websocket
消息字符串。因此,它会引发一个 AttributeError,它没有 done()
方法。
其次,callback=self.cb_receive_weight
这将调用cd_receive_weight
带有未来的方法,而不是消息。所以,那是行不通的。
我认为事情没有按预期工作可能是因为你在混合 yield
和回调。
记住,yield object
会自动调用 object.result()
。考虑:
response = yield self.ws.read_message()
以上,ws.read_message()
returns一个Future,但是yield
,会等到Future
有一个结果。当 Future 得到解析时,yield
将调用它的 result()
方法。
response
将等于该结果。
如果您正在使用 yield
,则您实际上并不需要使用回调。我建议不要
完全使用回调编码风格。避免使用它们并使用协程 (yield
)
在可能的情况下。
代码会更短,更有条理。
示例:
@gen.coroutine
def connect(self):
self.ws = yield websocket_connect(url)
self.run()
...
@gen.coroutine
def get_weight_from_global_network(self):
while True:
response = yield self.ws.read_message()
# do something with the response
self.cb_recieve_weight(weight=response)
虽然,我不能说这是否能解决您的问题。