Today I needed to read some data from a NetworkStream. First I tried Stream.Read-Method but then I noticed that it blocks my program.
Sometimes it seems to be meaningful to read the reference:
The implementation will block until at least one byte of data can be read, in the event that no data is available. Read returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file).
I wrote a litte example showing how to read from a NetworkStream the asynchronous way. Just in case someone else stumbles across this.
-
using System;
-
using System.Net;
-
using System.Net.Sockets;
-
using System.IO;
-
using System.Text;
-
using System.Threading;
-
-
namespace AsyncReadExample
-
{
-
-
public class State {
-
-
const int BUFFER_SIZE = 1024;
-
-
public byte[] Buffer;
-
public Stream Stream;
-
public String ReadResult;
-
-
public State() {
-
Stream = null;
-
ReadResult = String.Empty;
-
}
-
}
-
-
class MainClass
-
{
-
-
-
const int BUFFER_SIZE = 1024;
-
-
[STAThread]
-
static void Main(string[] args) {
-
-
IPAddress serverip = IPAddress.Parse("127.0.0.1");
-
server.Start();
-
-
TcpClient client = server.AcceptTcpClient();
-
NetworkStream stream = client.GetStream();
-
-
state.Stream = stream;
-
-
// nonblocking
-
IAsyncResult result = stream.BeginRead(
-
state.Buffer,
-
0,
-
BUFFER_SIZE,
-
state
-
);
-
-
// do something else here
-
someOtherTask();
-
-
// Wait until all data is read
-
terminate.WaitOne();
-
Console.WriteLine(state.ReadResult);
-
Console.ReadLine();
-
-
client.Close();
-
server.Stop();
-
}
-
-
private static void ReadCallback(IAsyncResult asyncResult) {
-
State state = (State) asyncResult.AsyncState;
-
Stream stream = state.Stream;
-
-
int read = stream.EndRead(asyncResult);
-
if (read> 0) {
-
state.ReadResult += Encoding.ASCII.GetString(state.Buffer, 0, read);
-
IAsyncResult result = stream.BeginRead(
-
state.Buffer,
-
0,
-
BUFFER_SIZE,
-
state
-
);
-
}
-
else {
-
terminate.Set();
-
}
-
}
-
-
private static void someOtherTask() {
-
Console.WriteLine("some other task");
-
}
-
-
}
-
}