Socket开发中的封包问题
现有包头结构和包体结构如下,如何封包后进行发送,Vb.net或C#的代码都可以。
包头和包体的定义和反序列化和序列化都已经实现,现在就差封包的步骤了!
不知道怎么实现,各位大哥帮帮忙。
封包=包头+包体
包头结构
MessageLength 4 char[4]
CommandID 10 char[10]
SequenceNumber 20 char[20]
包体结构
UserValidate 6 char[6]
UserNumber 21 char[21]
ValidateType 1 Integer
ValidatePassowd 16 char[16]
Reserve 8 char[8]
程序中的包头定义和包体定义及序列和反序列的程序
<StructLayout(LayoutKind.Sequential, Pack:=1, CharSet:=CharSet.Unicode)> _
Private Structure Header
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=5)> Public MessageLength As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=11)> Public CommandID As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=21)> Public SequenceNumber As String
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1, CharSet:=CharSet.Unicode)> _
Private Structure UserValidate
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=7)> Public UserValidate As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=22)> Public UserNumber As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=2)> Public ValidateType As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=17)> Public ValidatePassowd As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=9)> Public Reserve As String
End Structure
#Region "序列化,反序列化"
Private Function RawSerialize(ByVal _Structure As Object) As Byte()
Dim rawsize As Integer = Marshal.SizeOf(_Structure)
Dim buffer As IntPtr = Marshal.AllocHGlobal(rawsize)
Marshal.StructureToPtr(_Structure, buffer, False)
Dim rawdatas As Byte() = New Byte(rawsize) {}
Marshal.Copy(buffer, rawdatas, 0, rawsize)
Marshal.FreeHGlobal(buffer)
Return rawdatas
End Function
Private Function RawDeserialize(ByVal rawdatas As Byte(), ByVal anytype As Type) As Object
Dim rawsize As Integer = Marshal.SizeOf(anytype)
If (rawsize > rawdatas.Length) Then Return Nothing
Dim buffer As IntPtr = Marshal.AllocHGlobal(rawsize)
Marshal.Copy(rawdatas, 0, buffer, rawsize)
Dim retobj As Object = Marshal.PtrToStructure(buffer, anytype)
Marshal.FreeHGlobal(buffer)
Return retobj
End Function
#End Region