I have developed a TCP server by async pattern under .net4 in c# that handles hundreds of TCP connections simultaneously. It has been working without any problems for months, so, I have experiences with async sockets & co. in .net.
Now I have another project: this time I have to develop a TCP client, that connects to a server (one and only server, not more!) via TCP and sends commands to it, get responses and also handles incoming, server initiated notification messages.
Now I am a little bit confused. I am looking for the most efficient way to implement these features:
- it must send some commands asynchronously and get their response also asynchronously
- some commands should be sent synchronously and get response also synchronously
- it must listen for incoming notification TCP messages. So, these messages are initiated from server side, they don’t come as a response for a request
Which do you think the best pattern to implement it? How to listen incoming, server initiated requests, while also handling client initiated requests?
Thanks!
Request sample:
02/00059/O/60/07656765/2/1/1/50617373776F7264//0100//////61
Response sample:
00/00019/R/60/A//6D
Notification sample: 00/00114/O/52/0011456046589/01123404543////////////0000/568112131424////3//434241///0//////56312389921/020100///C3
It really depends on how the server formats the commands that are coming in. Let’s say, for example, they are in the form ” “.
The first thing I would do is write a socket class that handles reading data in and raising an event (say,
OnLine) for each “line” received (this is just an example, I have no idea what kind of format your command and messages are in).I would then implement a class that has this text-socket as a member, and subscribe to the line received event. This class would also have a dictionary of delegates that map to the possible commands that can be received from the server, e.g:
Note, I have used lambdas here, but sure don’t need to.