在网络流上反序列化system.outofmemoryexception

时间:2012-11-25 01:01:32

标签: visual-studio serialization deserialization out-of-memory binaryformatter

我有一个名为Cereal的可序列化类,其中显示了几个公共字段

<Serializable> Public Class Cereal
    Public id As Integer
    Public cardType As Type
    Public attacker As String
    Public defender As String
    Public placedOn As String
    Public attack As Boolean
    Public placed As Boolean
    Public played As Boolean
    Public text As String

    Public Sub New()

    End Sub
End Class

我的客户端计算机正在通过序列化向主机发送新的Cereal

'sends data to host stream (c1)
Private Sub cSendText(ByVal Data As String)
    Dim bf As New BinaryFormatter
    Dim c As New Cereal
    c.text = Data
    bf.Serialize(mobjClient.GetStream, c)
End Sub

主机监听流的活动,当有东西被放到它上面时,它应该将它反序列化为这里显示的新谷歌

'accepts data sent from the client, raised when data on host stream (c2)
Private Sub DoReceive(ByVal ar As IAsyncResult)
    Dim intCount As Integer

    Try
        'find how many byte is data
        SyncLock mobjClient.GetStream
            intCount = mobjClient.GetStream.EndRead(ar)
        End SyncLock
        'if none, we are disconnected
        If intCount < 1 Then
            RaiseEvent Disconnected(Me)
            Exit Sub
        End If

        Dim bf As New BinaryFormatter
        Dim c As New Cereal
        c = CType(bf.Deserialize(mobjClient.GetStream), Cereal)
        If c.text.Length > 0 Then
            RaiseEvent LineReceived(Me, c.text)
        Else
            RaiseEvent CardReceived(Me, c)
        End If

        'starts listening for action on stream again
        SyncLock mobjClient.GetStream
            mobjClient.GetStream.BeginRead(arData, 0, 1024, AddressOf DoReceive, Nothing)
        End SyncLock
    Catch e As Exception
        RaiseEvent Disconnected(Me)
    End Try
End Sub

当执行以下行时,我得到一个System.OutOfMemoryException,我无法弄清楚为什么这不起作用。

c = CType(bf.Deserialize(mobjClient.GetStream), Cereal)

该流是TCPClient流。我是序列化/反序列化和使用visual studio 11

的新手

1 个答案:

答案 0 :(得分:0)

我的arData只接受1024个字节,正如你在代码中再次启动监听器时所看到的那样。我已经多次提出这个问题了,因为现在我在图像中发送图像了。我现在超过3,000,000(或3MB),我认为我发送的最多是2MB。在我的代码中,有5或6个地方需要更新arData,而不仅仅是上面显示的那个。此外,提高这一点似乎并没有减慢发送极小数据的速度。