I'm learning networking and threading in C#. For that purpose I'm developing chat over network.
Currently I have basic communication between client - server (TCP). Server can work with multiple clients. But only client - server communication. Basically client sends ASCII encoded message to server, then server decodes it and shows in console.
By now I want to implement Client-Client communication.
Suppose we have online list of clients in each client and message box for sending message to each client.
Next step is clicking button, which will compose a Socket and send, then Server should understand whom is addressed message.
So, what should be my structure of message, and how I should understand in Server, whom addressed message?
Generally I don't need code, I want theory. Simple and short. Maybe tutorials?
I have looked into XMPP. It's very heavy. I just need direction, how I can do this. My goal is to learn, not implement it and forgot.
TCP is stream based which means that you will never know, with the help of TCP, when a message begins and ends. Any message/protocol design needs to address that.
There are two ways to detect when a message ends. The first way is to add a delimiter at the end of message, and the second way is to include the length in a header.
HTTP uses both. It uses an empty line to determine when the header ends. And in the header it got a Content-Length header which tells how large the body is.
For binary protocols I suggest that you use a fixed length header where the first integer (4 bytes) is a version and the second integer is the body length. In this way you can easily switch header layout between versions (since the version is the first integer).
For text protocol it really depends on how the message contents looks like. The problem is that the content may not include the delimiter to be used (which can be hard if you are transporting chat messages). You could of course escape the delimiter if it exists in the actual chat message. But imho a better approach is to use a header/body layout like HTTP (since it's also quite easy to parse and you can have X number of headers without having to change the parser).
A message would look like:
From: Arne
To: #ChannelName
WrittenAt: 2011-07-03 12:00 GMT
Content-Length: 16
This is a text
Notice that the length is 16, this is since the new line was included in the body.
As for client-client communication I would always go through the server if you are a beginner. It's a lot easier since otherwise you have to make sure that at least one of the clients is not behind a router (or it will be impossible to deliver the message).
Just check the To
header if it's for a chat room or a user.