Calling BeginRead from NetworkStream

Good. I want to connect to a Socket and read the network stream using the System.Net.Sockets.NetworkStream class. This is what I have so far:

 NetworkStream myNetworkStream; Socket socket; socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IPv4); socket.Connect(IPAddress.Parse("8.8.8.8"), 8888); myNetworkStream = new NetworkStream(socket); byte[] buffer = new byte[1024]; int offset = 0; int count = 1024; myNetworkStream.BeginRead(buffer, offset, count, ??, ??); 

Now I need AsyncCallback and Object state to complete my BeginRead method, but I'm not even sure if this will work. I am a little lost at this point! Where do I need to go from here?

+4
source share
1 answer

In principle, when you call the Begin* method during an asynchronous operation, there must be a call to the corresponding End* operator (for more information see the Overview of Asynchronous Programming in MSDN , in particular, the section "Finishing the Asynchronous Operation").

However, you usually want to pass a method / anonymous method / lambda expression that will do one or two things:

1) Call the appropriate End* method, in this case Stream.EndRead . This call will not be blocked during the call because the callback will not be called until the operation is completed (note that if an exception occurs during an asynchronous call, this exception will be called when the End* method is called).

2) It is possible to start a new asynchronous call. In this case, it is assumed that you want to read more data, so you should start a new call to Stream.BeginRead

Assuming you want to do # 2, you can do the following:

 // Declare the callback. Need to do that so that // the closure captures it. AsyncCallback callback = null; // Assign the callback. callback = ar => { // Call EndRead. int bytesRead = myNetworkStream.EndRead(ar); // Process the bytes here. // Determine if you want to read again. If not, return. if (!notMoreToRead) return; // Read again. This callback will be called again. myNetworkStream.BeginRead(buffer, offset, count, callback, null); }; // Trigger the initial read. myNetworkStream.BeginRead(buffer, offset, count, callback, null); 

However, if you use .NET 4.0, it becomes much easier with the FromAsync method on the TaskFactory class .

+13
source

Source: https://habr.com/ru/post/1380624/


All Articles