tcp - 使用 protobuf-net 反序列化 Protocol Buffer 时如何指定流长度?

标签 tcp stream protocol-buffers protobuf-net

我正在尝试使用 Protocol Buffers 通过 TCP 连接将整数从服务器发送到客户端。我相信我的服务器正在向流中写入内容,但是当客户端尝试从网络流中反序列化时,我的代码会无限期地暂停。我的直觉告诉我,客户端不知道流的长度,所以它不知道读取何时完成,但是 Deserialize 方法没有长度输入,所以我不确定如何实现这个。下面是我的原型(prototype)定义、服务器和客户端的代码。

原型(prototype)定义

Public Class Proto
<ProtoContract()>
Public Class TCP
    <ProtoMember(1)>
    Public Property Command As Integer

End Class
End Class

服务器代码

    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),解释为“Creates a new instance from a protocol-buffer stream”

我意识到有一种方法允许您使用长度前缀进行序列化和反序列化,恰本地命名为“SerializeWithLengthPrefix”

我担心的是,将来我不会编写服务器代码,我相信服务器代码将使用 C++,它可能有也可能没有前缀长度选项。

最佳答案

我意识到有一种方法允许您使用长度前缀进行序列化和反序列化,恰本地命名为“SerializeWithLengthPrefix”

我担心的是将来我不会编写服务器代码,而且我相信服务器代码将使用 C++,它可能有也可能没有前缀长度选项。

关于tcp - 使用 protobuf-net 反序列化 Protocol Buffer 时如何指定流长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464926/

相关文章:

python - 从部分 google protobuf 消息中检索信息

dart - 在 Dart 中使用 Sink 和 Pipe 与 Streams 有什么区别?

serialization - 在 protobuf 消息中存储单个字节

c - 在套接字编程 C 中,将 Int 值写入服务器会将其转换为 -1

Swift 通过 TCP 套接字发送十六进制数据

javascript - 使用 fetch 或 new Request() 创建的请求具有未定义的主体

c++ - 用我自己的方法扩展 Protobuf

protocol-buffers - Protocol Buffer : How to use the --encode command on console

java - Java ServerSocket accept client后如何获取绑定(bind)到同一本地端口的新套接字?

Python:tarfile 流