连接完成后,将对象发送到客户端计算机

时间:2012-11-17 01:38:32

标签: visual-studio object serialization client

我有一个目前用作聊天服务器的程序。这是一款基于回合制的纸牌游戏,带有聊天框,可与对手进行交流。聊天的东西都可以通过连接工作,但是我需要开始向对手发送某些牌,所以当我玩牌时,我的对手会在他的屏幕上看到它。我希望客户端计算机接收对象或对象集合,根据其属性确定卡类型,然后将卡放在正确的位置。发送和接收部分是我不明白如何完成的。从我读过的,这需要序列化,我只是不知道从哪里开始。请协助!我正在使用visual studio。

1 个答案:

答案 0 :(得分:0)

再次回答我自己的问题...我最终创建了一个名为card container的新类,其中包含cardType作为字符串,card id作为int。卡容器还有其他属性,所以我知道卡的位置。然后我序列化了卡片容器(以下代码中的'cc')并按如下方式发送:

Dim cc as new CardContainer
cc.id = card.id
cc.cardType = card.GetType.ToString
cc.discard = true

Dim bf As New BinaryFormatter
Dim ms As New MemoryStream
Dim b() As Byte

'serializes to the created memory stream
bf.Serialize(ms, cc)
'converts the memory stream to the byte array
b = ms.ToArray()
ms.Close()

'sends the byte array to client or host
SyncLock mobjClient.GetStream
    mobjClient.GetStream.Write(b, 0, b.Length)
End SyncLock

客户端在其TCPClient上侦听任何内容并使用以下代码获取该卡:

    Dim intCount As Integer

    Try
        SyncLock mobjClient.GetStream
            'returns the number of bytes to know how many to read
            intCount = mobjClient.GetStream.EndRead(ar)
        End SyncLock
        'if no bytes then we are disconnected
        If intCount < 1 Then
            MarkAsDisconnected()
            Exit Sub
        End If

        Dim bf As New BinaryFormatter
        Dim cc As New CardContainer
        'moves the byte array found in arData to the memory stream
        Dim ms As New MemoryStream(arData)

        'cuts off the byte array in the memory stream after all the received data
        ms.SetLength(intCount)
        'the new cardContainer will now be just like the sent one
        cc = bf.Deserialize(ms)
        ms.Close()

        'starts the listener again
        mobjClient.GetStream.BeginRead(arData, 0, 3145728, AddressOf DoRead, Nothing)

根据cardcontainer确定的数据,客户端现在调用哪种方法。例如,当收到此消息时,创建的cc将传递给我的CardReceived方法,然后该方法有一堆if,elseif语句。其中之一就是

ElseIf cc.discard = true then
'makes a new card from the id and cardType properties
dim temp as new object = MakeCard
'discard method will find the correct card in the Host's known hand and discard it to the correct pile
Discard(temp)
相关问题