I’m trying to set up some Network stuff. For this reason I need to send and receive data over network. In particular HTTP-Messages. I want to implement this with asynchronous Methods in C#. When im receiving the HTTP-Response from a Webserver, I want to receive data until the webserver closed the connection or (connection: keep alive) until i received all bytes of the HTTP-Response. I already tried to set this up method but failed. Can you tell me how to implement this. I’ve seen this example on msdn:
private static void Receive(Socket client) {
try {
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
With the State Object:
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
If I would use similar code to this, I’m afraid to run into horrible sideeffects because all Threads use the same state-object. Furthermore, I have to resend the data received data immediately.
I tried to implement the asynchronous Receive method. Well, its not finished yet, but the basic structure should be clear.
Every peace of the message received, is resendet to Browser. To ensure that the Browser gets those peaces in the right order, I’ve got the SendingToBrowserCompleted-AutoResetEvent here. If your interested in more code, just ask.