我正在使用服务器和客户端。客户端只应反序列化收到的protobuf消息,如果字符串"是"收到了。
编辑:
protobuf的第一条消息很好。但是,如果我想一次发送多条消息,它会给我:
System.OverflowException:Number overflow。 在ProtoBuf.ProtoReader.TryReadUInt32Variant(System.IO.Stream source,System.UInt32& value)
我通读了这个链接,但我无法弄清楚在我的情况下应该做些什么...
我正在使用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消息之前使用字符串来解决这个问题?有可能吗?
答案 0 :(得分:0)
尝试在不同的套接字中分离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();
我没有测试或编译代码。