我正在尝试使用Protocol Buffers通过TCP连接从服务器向客户端发送整数。我相信我的服务器正在向流写入内容,但是当客户端尝试从网络流反序列化时,我的代码会无限期地暂停。我的直觉告诉我,客户端并不知道流的长度,因此它不知道读取何时完成,但是反序列化方法没有长度输入所以我&# 39;我不知道如何实现这一点。下面是我的原型定义,服务器和客户端的代码。
PROTO DEFINITION
Dim commandStuff As New Proto.TCP
Console.WriteLine("Enter command number")
commandStuff.Command = Console.ReadLine()
Dim myIP As IPAddress = IPAddress.Parse("my address")
Dim myServer As New TcpListener(myIP, 800)
myServer.Start() 'starts listening,
Console.WriteLine("Waiting for connection")
Dim myClient As TcpClient = myServer.AcceptTcpClient() 'Accepts client, pauses program until finds a client
Console.WriteLine("Connected")
Dim myStream As NetworkStream = myClient.GetStream
ProtoBuf.Serializer.Serialize(Of Proto.TCP)(myStream, commandStuff) 'write the instance commandStuff to the stream myStream
Console.WriteLine("Stuff has been written")
Console.ReadLine()
服务器代码
Dim IP As IPAddress
IP = IPAddress.Parse("my address")
Dim myClient As New TcpClient
myClient.Connect(IP, 800)
Console.WriteLine("Connected")
Dim myStream As NetworkStream
myStream = myClient.GetStream
Console.WriteLine("Stream created")
Dim ReceivedCommand As New Proto.TCP
ReceivedCommand = ProtoBuf.Serializer.Deserialize(Of Proto.TCP)(myStream)
Console.WriteLine("Stream deserialized")
Dim Command As Integer
Command = ReceivedCommand.Command
Console.WriteLine(Command)
Console.ReadLine()
此代码完全没有任何问题地运行
客户代码
ReceivedCommand = ProtoBuf.Serializer.Deserialize(Of Proto.TCP)(myStream)
此代码卡在Deserialize(Of T)(source As System.IO.Stream)
反序列化的格式为{{1}},解释为"从协议缓冲流创建新实例"
我意识到有一种方法允许你使用长度前缀序列化和反序列化,适当地命名为" SerializeWithLengthPrefix"
我担心的是,将来我不会写服务器代码,我相信服务器代码将使用C ++,这可能有也可能没有前缀长度的选项。
答案 0 :(得分:0)
我意识到有一种方法允许你使用长度前缀序列化和反序列化,适当地命名为" SerializeWithLengthPrefix"
我担心的是,将来我不会写服务器代码,我相信服务器代码将使用C ++,这可能有也可能没有前缀长度的选项。