如何创建数据包标头?

时间:2012-03-07 16:53:32

标签: .net vb.net sockets networking packet

基本上我通过客户端/服务器连接发送和接收图像,字符串和文件。我可以很容易地使用协议进行字符串命令,但我无法区分传入的数据[如果数据是图像或其他什么,然后按照说明进行操作]。

那么如何使用Dim缓冲区作为byte()生成数据包?

2 个答案:

答案 0 :(得分:1)

我只想猜测你想要做什么。如果您使用TCPListener来处理传入的HTTP连接,您可以这样响应:

    Private Sub ServePNG()

        Dim stream As NetworkStream = mytcpclient.GetStream

        Dim Content As Byte() = System.IO.File.ReadAllBytes("image.png")

        Dim sb As New System.Text.StringBuilder
        sb.Append("HTTP/1.0 200 OK" + ControlChars.CrLf)
        sb.Append("Content-Type: image/png" + ControlChars.CrLf)
        sb.Append("Content-Length: " + Content.Length.ToString + ControlChars.CrLf)
        sb.Append(ControlChars.CrLf)

        Dim Header() As Byte = Encoding.ASCII.GetBytes(sb.ToString)
        stream.Write(Header, 0, Header.Length)
        stream.Write(Content, 0, Content.Length)

        client.Close()

    End Sub

我直接从image.png

获取字节数组

答案 1 :(得分:0)

你可以创建一个包含Header Property的新类,然后你可以序列化该类,然后将其转换为字节数组

示例:


Serializable()
    Public class Packet
    dim _header as packetHeader
    dim _data as byte()
    Public Property Header as packetHeader
    Get
    Return _Header
    End Get
    Set (byval value as packetHeader)
    _header = value
    End Set
    End Property
    Public Property Data as Object
    Get
    Return _Header
    End Get
    Set (byval value as Object)
    _data = value
    End Set
    End Property
    Public Sub New()
    End Sub
    Public Sub New(Byval header as packetHeader, Byval data as Object)
    _header = header
    _data = data
    End Sub
    Public Shared Function Serialize(myPacket as Packet) as Byte()
    Dim fs as New MemoryStream
    Dim formatter as New BinaryFormatter
    formatter.Serialize(fs, myPacket)
    Return fs.ToArray
    End Function
    Public Shared Function Deserialize(strm() as Byte) as Packet
    Dim fs as New MemoryStream(strm)
    Dim formatter as New BinaryFormatter
    Return DirectCast(formatter.Deserialize(fs),Packet)
    End Function
    End Class
    'Example of use
    Public Enum packetHeader as Integer
    Text = 0
    Image = 1
    'etc
    End Enum
    'Inside button click event (sending the packet)
    Dim bitmap as new Bitmap("C:/example.png")
    Dim data as Object =  bitmap
    Dim myPacket as new Packet(packetHeader.Image, data)
    dim buffer() as byte = Packet.Serialize(myPacket)
    'to deserialize the packet and check the header
    Dim buffer() as byte = stream.Read
    Dim myPacket as Packet = Packet.Deserialize(buffer)
    Select myPacket.Header
    Case packetHeader.Image
    Dim image as Bitmap
    image = DirectCast(myPacket.Data, Bitmap)
    Case packetHeader.Text
    Dim str as String
    str = DirectCast(myPacket.Data, String)
    End Select
    'do your proccess inside the Select statement