Protobuf如何多次接收字符串和对象
本文关键字:字符串 对象 何多次 Protobuf | 更新日期: 2023-09-27 18:16:51
我使用一个服务器和一个客户端。只有当接收到字符串"yes"时,客户端才应该反序列化接收到的protobuf消息。
编辑:protobuf的第一条消息被很好地接收。但是,如果我想一次发送多个消息,它会给我:
系统。OverflowException:数量溢出。在ProtoBuf.ProtoReader。TryReadUInt32Variant(先。流源,System.UInt32&值)
我看了这个链接,但我不知道我该怎么做。
我使用TCP套接字。下面是一个示例代码:
c#客户端:
TcpClient tcpClient = new TcpClient(host, port);
NetworkStream netStream = tcpClient.GetStream();
StreamReader reader = new StreamReader(netStream);
while(true)
{
// Read multiple messages one after another.
string message = reader.ReadLine();
if(message.Equals("yes"))
{
Command command = Serializer.DeserializeWithLengthPrefix<Command> (netStream, PrexiStyle.Base128);
BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create));
bw.Write(command.File);
bw.Flush();
bw.Close();
}
}
Java服务器:
OutputStream outputStream = clientSocket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
try{
// send "yes" and the protobuf messages ten times one after another
for(int i=0; i<10; i++)
{
writer.println("yes");
command.writeDelimitedTo(outputStream);
}
}catch(Exception e)
e.printStackTrace();
}
finally{
outputStream.close();
clientSocket.close();
}
我的。proto文件和proto合约具有相同的类型。如果我不想发送字符串,而只想发送protobuf消息,它就会工作。
我如何在反序列化protobuf消息之前使用字符串来解决这个问题?这可能吗?
尝试在不同的套接字中分离protobuf数据和其他数据。添加了一个while循环,以便能够从服务器读取多个消息。
using System.Threading;
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
// Protobuf data is read on this socket
TcpClient tcpClient = new TcpClient(host, port);
NetworkStream netStream = tcpClient.GetStream();
StreamReader reader = new StreamReader(netStream);
BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create));
bool running = true;
while(running)
{
bw.Write(Serializer.DeserializeWithLengthPrefix<Command>(netStream, PrexiStyle.Base128).File);
}
bw.Flush();
bw.Close();
}).Start();
// Other data is read no this socket
TcpClient tcpClientForOtherStuff = new TcpClient(host, port);
NetworkStream netStream = tcpClientForOtherStuff.GetStream();
StreamReader readerForOtherStuff = new StreamReader(netStream);
string message;
bool running = true;
BinaryWriter bwForOtherStuff = new BinaryWriter(File.Open(path2, FileMode.Create));
bool running = true;
while(running) bwForOtherStuff.Write(readerForOtherStuff.ReadLine());
bwForOtherStuff.Flush();
bwForOtherStuff.Close();
我没有测试或编译代码。