I am looking for best practices to meet the following requirements:
- A structure that processes multiple client sockets in asynchronous mode.
- Each incoming message protocol determines that each message has a format string and is marked in full by the string character "\ n".
- I have full control over the client side, but not with the server. The server receives and sends string messages with a line symbol to mark the end of the message.
- I want to be able to send messages through each connected socket at any given time (each socket can receive and send messages).
- Incoming messages must be sent via a callback.
- I want to be able to choose in my implementation whether all incoming full messages from all connected sockets are routed to one callback or each socket client implements its own callback.
- I connect a maximum of 4 clients / sockets. Therefore, I am looking for offers that use such a limited number of sockets, but they are able to manage all of these at the same time.
I wonder if the environment in which I use BeginReceive and EndReceive with the EndReceive implemented is the most advanced target set .Net 4.5. Is there a better solution, for example, using NetworkStream or other API options? What really bothers me with implementing BeginReceive / EndReceive is that after EndReceive I need to call BeginReceive again and register the callback again. That sounds like a terrible amount of overhead to me. Why can't new async data be added at any time, and at the same time, a different context creates complete messages, which are then routed through the raised event?
The argument for using IAsyncResult is often indicated in the fact that stream processing is performed, but that is against the following: Using NetworkStream and just reading and writing to the stream. As mentioned, only text messages are exchanged, and each message on the protocol is marked with a full line symbol. A separate task / stream will poll the stream analyzer (based on the network stream) through ReadLine() . It could probably be easier, right?
Basically I ask a question, how to make the following code really asynchronous?
public class SocketClient { private TcpClient client; private StreamReader reader; private StreamWriter writer; public event Action<string> MessageCallback; public SocketClient(string hostname, int port) { client = new TcpClient(hostname, port); try { Stream stream = client.GetStream(); reader = new StreamReader(stream); writer = new StreamWriter(stream); writer.AutoFlush = true; //Start Listener on port StartListener(); } catch (Exception e) { throw new Exception(e.ToString()); } } public void StartListener() { Task task = Task.Factory.StartNew(() => { while (true) { if (MessageCallback != null) { MessageCallback(reader.ReadLine()); } //Thread.Sleep(200); } }); } }
c # asynchronous sockets tcp networkstream
Matt wolf
source share