gpt4 book ai didi

python gevent websocket 客户端收到错误 "DecodeError: Truncated message"回显 Protocol Buffer 消息

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:30 24 4
gpt4 key购买 nike

我有一个简单的 websocket 服务器,它将所有消息回显给客户端。

import gevent
from geventwebsocket.resource import WebSocketApplication
from geventwebsocket.server import WebSocketServer
from geventwebsocket.resource import Resource
import ams_pb2

class AMSWebSocketServer(WebSocketApplication):
def __init__(self, ws):
super(AMSWebSocketServer, self).__init__(ws)
pass

def on_open(self):
pass

def on_message(self, message):
print 'received message'
print message
if message is None:
print 'message none'
return

print 'echo message back'
self.ws.send(message)

def on_close(self, reason):
print "connection closed"
gevent.sleep(0)


resource = Resource({'/': AMSWebSocketServer})

服务器是使用gunicorn命令生成的

gunicorn -k "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" -b 127.0.0.1:9000 gunicorn_test:resource

我有一个测试客户端,它发送要回显的 websocket 消息

from ws4py.client.threadedclient import WebSocketClient
import ams_pb2


class DummySwitch(WebSocketClient):
def closed(self, code, reason=None):
pass

def received_message(self, msg):
if msg is None:
print 'none'
return
print 'received message'
ams_message = ams_pb2.AMSConfig()
ams_message.ParseFromString(msg)
print ams_message
print msg


if __name__ == '__main__':
end_point = 'ws://127.0.0.1:9000'

client = DummySwitch(
end_point,
headers=[
]
)
client.connect()

print 'sending message'

AMSConfig = ams_pb2.AMSConfig()
AMSConfig.CliConfig = True
print AMSConfig
msg = AMSConfig.SerializeToString()

#msg = 'Hello'
print msg

client.send(msg)

client.run_forever()

我的 protobuff 文件是: 封装ams;

message AMSConfig {
optional bool CliConfig = 1;
}

每当我的客户端向服务器发送 protobuff 消息时,我都可以看到它在服务器中被解析,但是当服务器将相同的消息回显给客户端时,客户端会因以下原因而失败:

文件“client_test.py”,第 15 行,在 receive_message 中 ams_message.ParseFromString(msg) 文件“/usr/lib/python2.6/site-packages/google/protobuf/message.py”,第 186 行,ParseFromString self.MergeFromString(序列化) 文件“/usr/lib/python2.6/site-packages/google/protobuf/internal/python_message.py”,第 847 行,MergeFromString raise message_mod.DecodeError('消息被截断。')解码错误:消息被截断。

因此,我修改了代码以发送一个简单的字符串,我看到发送到服务器的“Hello”字符串正在回显,并且客户端能够打印该消息。但是,客户端无法解析回显的 protobuff 消息。

我无法理解为什么字符串的回显有效,但对于 Protocol Buffer ,它在我的示例中不起作用。

感谢您的帮助。

最佳答案

我在客户端遇到同样的问题,但这可以通过扩大客户端代码中的接收缓冲区大小来解决。例如:

maxpkglen = 1024 * 1024 // original maxpkglen = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(req, (server, port))
rsp, server = s.recvfrom(maxpkglen)
s.close()

关于python gevent websocket 客户端收到错误 "DecodeError: Truncated message"回显 Protocol Buffer 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27466135/

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