Search code examples
c#.netmultithreadingsocketstcpclient

.Net Socket enhancement to support ACKs and Chat?


I have a server which can deal with many multiple client requests.

The server uses a Socket and TcpClient - for every client , it opens a new thread.

Each client sends data to the server and the server response.

But HOW do I "send a data" :

  • Client : sends a byte which represents : "I want to send data"

  • Server : sends Ok I agree ( 1 byte of ack)

  • Client: Sends The number of the bytes - length of the data

  • Server : sends Ok I can handle it

  • Client : sends the whole data

  • Server : sends Ok

I can also send files

It's all working great.

Question

Here comes the problem :

Those commands ( which I've written) are user actions.

Now I need to add a chat to this action screen

It is not a problem :

I will open a new thread which will always be in "listen mode" for messages

But :

That thread which will always listen , will also intercept the Ack messages (which i've written above) from the server !

I dont want to open a new connection channel just for the chat.

EVen if I add a response type ( ACK or CHAT_MESSAGE) - it will be a problem because responses for the user action will end up in the listening chat thread.

How can I ( ideally) solve this architecture problem ? Am I in the wrong direction ?


Solution

  • If you don't want to open a new connection for the chat you'll have to deal with a more complex wire protocol:

    You'll have to message-frame data and chat message in a way that allows the server to find out which of the two is coming through right now. Depending on that data is being received it needs to be treated differently.

    It doesn't make sense to read from the same TCP connection with more than one thread. TCP is not message based. The bytes that are incoming could be scattered arbitrarily across threads. A single thread needs to find out what type of data is coming and dispatch it.