0

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

4

1 回答 1

0

再次回答我自己的问题...我最终创建了一个名为 card container 的新类,其中包含作为字符串的 cardType 和作为 int 的卡 ID。卡片容器还有其他属性,所以我知道卡片的去向。然后我序列化了卡片容器(在下面的代码中是'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)
于 2013-01-09T19:18:34.830 回答