2012-11-17 64 views
0

我有一個程序,當前作爲聊天服務器工作。這是一個基於回合的紙牌遊戲,有一個聊天框可以與對手進行交流。聊天內容都是通過連接進行的,但是我需要開始向對手發送某些卡片,所以當我玩牌時,我的對手會在他的屏幕上看到它。我希望客戶端計算機能夠接收對象或對象集合,根據其屬性找出卡的類型,然後將卡放在正確的位置。發送和接收部分是我不知道如何完成的。從我讀過的,這需要序列化,我只是不知道從哪裏開始。請協助!我正在使用visual studio。連接後發送對象到客戶端計算機

回答

0

再次回答我自己的問題......我最終創建了一個名爲card container的新類,它包含cardType作爲字符串和card id作爲int。卡容器還有其他屬性,所以我知道卡的位置。然後我序列化的卡容器(這是在下面的代碼「抄送」),併發送它,如下所示:

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) 
相關問題