2014年11月15日 星期六

[.NET] TCP使用筆記1--物件序列化/反序列化傳送接收

將物件序列化後傳送串流 ------> 收到串流後反序列化還原物件

Import System.Runtime.Serialization.Formatters.Binary
<Serializable()>
Public Class MySerializableClass   ' Define a Class which is able to be serialized '
    Property s As String = "abcdedfg"
    Property i As Integer = 50
    Property f As Double = 3.14159256
End Class

Dim clientSend As TcpClient = New TcpClient()        'used to send stream'
Dim clientReceive As TcpClient = new TcpClient()     'used to receive stream'

Sub serializeAndSend()
   Dim bf As BinaryFormatter = New BinaryFormatter()             
   bf.Serialize(clientSend.GetStream(), New MySerializableClass())   ' Serialize object and write into net-stream '
End Sub

Function receiveAndDeserialize() As Object
   Dim bf As BinaryFormatter = New BinaryFormatter()             
   return bf.Deserialize(clientReceived.GetStream())   ' stream received and deserialize to object'
End Function

其中BinaryFormatter可用在任何串流的序列化/反序列化(檔案串流、網路串流、記憶體串流…等等) ,
可延伸此法將物件資料存入/讀出磁碟,比方機台參數設定...等等,或是做大型物件的記憶體內複製(應用記憶體串流)。

沒有留言:

張貼留言