سؤال

I have a card game program, and so far, the chat works great back and forth over the TCPClient streams between host and client. I want to make it do this with serializing and deserializing so that I can also pass cards between host and client. I tried to create a separate TCPClient stream for the passing of cards but it didn't work and figured it may be easier to keep one TCPClient stream that gets the text messages as well as cards. So I created a class, called cereal, which has the properties for the cards that will help me rebuild the card from an embedded database of cards on the other end. Is there a way to make my program figure out whether a card has been put in the stream or if it's just text in the stream so I can properly deserialize it to a string or to a cereal? Or should I add a string property to my cereal class and when that property is filled in after deserializing to the cereal, i'll know it's just text (if that field is empty after deserializing i'll know it's a card)? I'm thinking a try catch, where it tries to deserialize to a string, and if it fails it will catch and cast as a cereal. Or am I just way off base with this and should choose another route? I'm using visual studio 2011, am using a binaryformatter, and am new to serializing/deserializing.

هل كانت مفيدة؟

المحلول 2

Ended up creating a container class which is serializeable. If I am sending text to the other computer, I set the text property of the container to whatever the text is. Then when this container is received, if it has text, the receiving computer will display the text. If the received container contains a card, it will create the card and put it where it needs to go based on additional properties found in the received container. If it is a discard, then it finds the card based on additional properties in the container, and discards it to the correct pile. I also included a command as String property in the container, so if all other properties are false, it will see if the command property has a string or not. If so, calls the command received method and finds the correct command and executes the code. Works great so far.

نصائح أخرى

This should work for you. Send a BaseMessage over the wire and then check which type came in.

namespace ConsoleApplication3 { class Program { static void Main(string[] args) { BaseMessage bm = new CardMessage(); if (bm.GetType() == typeof(CardMessage)) { } } }

class BaseMessage : ISerializable
{
}

class ChatMessage : BaseMessage
{
}

class CardMessage : BaseMessage
{
}

}

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top