Reputation: 156
I want to create a very simple chat program using WCF.
When somebody logs in, the server side creates a ChatMember object, adds it to a list, and it sends back to the client to further usage. Later on the client sends back the forementioned ChatMember object and the server tries to find it in the list, but it cannot. The list still has an object, but the reference of the two objects are seemingly different. Why? Is it normal?
server side:
public class Service1 : IService1
{
static List<ChatMember> members = new List<ChatMember>();
public DataMember Login(string name)
{
var member = new ChatMember(name);
members.Add(member);
return member;
}
public bool Logout(DataMember member)
{
bool foundAndRemoved = members.Remove(member);
}
}
[DataContract]
public class ChatMember
{
[DataMember]
public string Name {get;set;}
... other properties which are either or not DataMembers
}
client side:
void Stuff()
{
Service1Client client = new Service1Client();
ChatMember me = client.Login("testName");
bool retVal = client.Logout(me);
}
Upvotes: 0
Views: 59
Reputation: 66
The objects are equal (same name) but each time when an object gets passed over the network a new instance will be generated by the DataContractSerializer. I would ensure that each chat member has an unique id and then use a dictionary to hold all the chat members. This way it won't matter if the references are not the same because you use an unique identifier. The Guid string will be generated on the client side but you also do it on the server side. Then you will not transfer the members name but the ChatMember object itself. This way you can also add other properties to a ChatMember like e.g. age, sex or interests.
public class Service1 : IService1
{
private static Dictionary<string, ChatMember> members = new Dictionary<string, ChatMember>();
public ChatMember Login(ChatMember member)
{
members.Add(member.Guid, member);
return member;
}
public bool Logout(ChatMember member)
{
bool foundAndRemoved = members.Remove(member.Guid);
return foundAndRemoved;
}
}
[DataContract]
public class ChatMember
{
[DataMember]
public string Guid { get; set; }
[DataMember]
public string Name { get; set; }
public ChatMember(string name)
{
Guid = new Guid().ToString();
Name = name;
}
}
Upvotes: 1
Reputation: 3723
The objects get serialized and deserialized when being sent over wcf so they are not actually the same object on each side. It would be better to pass as ID from the client and then have the server find the object by ID.
Upvotes: 3