public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 2048;
public byte[] buffer = new byte[BufferSize];
public MemoryStream receivedObject = null;
public bool lengthRead = false;
public long dataLength = 0;
}
private void Receive()
{
try
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (
Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
if (!state.lengthRead)
{
state.dataLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(state.buffer, 0));
state.lengthRead = true;
state.receivedObject = new MemoryStream(/*Convert.ToInt32(state.dataLength) + 4*/);
}
state.receivedObject.Write(state.buffer, 0, bytesRead);
if (state.receivedObject.Length > state.dataLength)
{
Console.WriteLine("Receive done. Received {0} bytes, expected {1}.", state.receivedObject.Length, state.dataLength);
Receive();
}
else
{
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
else
{
Console.WriteLine("Connection closed by server.");
}
}
catch (
Exception e)
{
Console.WriteLine(e.ToString());
}
}