Hello, how can I write a network client that could set an event for an action. For example:

void main() { MyClient client=new MyClient() client.receive+=my_receive; client.Start(9274); } void my_receive(byte[] data) { Console.WriteLine(Encoding.UTF8.getString(data)); } 

Simply, all the examples that I found, TCPClient razluyut with sending only one message. and immediately thereafter closed

  • Head (usually via fingers). - More seriously, imagine the simplest chat (for the console window). The client starts and sends the server a message about the new member. Then its one part (stream 1) reads input from the console and sends these lines to the server. The other part (stream 2) reads the lines sent by the server and displays them on the screen. Think it over. And write. - avp
  • I understand correctly that getStream (). Read () on an instance of TCPClient blocks program execution until there is no data? like AcceptClient () on TCPListener. - alexmelyon
  • Yes. Only more correct is the analogy with Console.Read - avp

1 answer 1

You can use the following technique. NetworkStream 's and TCPClient 's (depending on what they use) have asynchronous BeginRead / EndRead methods that return control instantly, and upon completion of the operation, call the transferred callback method. In a callback for BeginRead call EndRead and then BeginRead with the same callback. It turns out a vicious circle: after the completion of reading, you start reading again, and the flow is not blocked. In a callback, you can pull any event that is accessible from the outside.

This technique is described in more detail, for example, here: Sending objects via high speed asynchronous sockets in C # .