For a school assignment we have to make a client server chat program in C#. I have never done any networking in the past before so its very confusing for me. I read a book on C# networking, and I was able to make a very basic chat that works using binary readers and writers and a TCP socket. However for the assignment I have to make the client list all connected users. Now, how would I make it so that the client only reads the stream for a list when someone disconnects or connects on the server. I could make it so that the clients is always downloading a new list, but I feel that’s a lot of redundant data being sent.
On a side note, I’m confused with how the client/server knows what the data in the stream is. So far I only have a string being sent through the stream which represents a message. Is there a way to attach some sort of signature or something to the data being sent so that the server or client knows that that specific data is the username or perhaps a message to be displayed.
Edit:
I’m having issues with the stream. I have a method that’s running in its own thread that’s always checking for information being sent. Its listing for both a string that’s a message to display message and a List containing users connected. The problem is that the order of the data being sent isn’t always in a consistent order. Sometimes the message is first, others the list is, and sometimes its only a message in the stream. Is there a way to tell what data is being read? Here is my client side listener.
private void incoming()
{
while (true)
{
try
{
string read = reader.ReadString();
if (read.Length > 0)
lbOutput.Items.Add(read);
lbUsers.Items.Clear();
List<string> users = (List<string>)binaryFormatter.Deserialize(stream);
foreach (string user in users)
lbUsers.Items.Add(user.ToString());
}
catch { lbOutput.Items.Add("Error reading the stream"); }
}
When a new client connects, it should send a message to the server to inform it that it has connected and ask it to store its name. Then the server can broadcast a message to all other clients with the new list (or just the name of the new client). Rough outline:
In parallel, you are receiving messages from clients to be routed (I assume). When a client leaves, it will again send a disconnect message and the server can broadcast the change to the rest of the clients.
If you want to work with more than just bytes and strings, you can try to send entire object by serialization. Have a look at this tutorial: http://msdn.microsoft.com/en-us/magazine/cc301761.aspx.