Asynchronous Socket Transfer in C#
Posted on 2004-04-26
Hi there, I am trying to make an FTP component and I need asynchronous file transfer. For the moment everything works fine, but I want to add a transfer progress bar. To do that I need to track the numer of bytes that have been received by the destination host.
I have to functions: the first one is the one that I call whan I begin a file transfer, and the second one is the callback function for the asynchronous transfer. In the state object I have the file that I will transfer, the socket, and the number of bytes transfered.
I have 2 problems:
1. I want to throw an event when the transfer is completed, but then Socket.EndSend() method blocks only for the time the bytes are sent, and i actualy need to send the event when the bytes are received. How can I ensure that the bytes have been succesfully received? I mean, after the Socket.EndSend() method returns, even if I close the socket, the data will still arive shortly.
2. I want to throw an event once every 512 bytes are sent. Any idea?
public void SendFile()
m_startTick = Environment.TickCount;
// Create the state object.
DataStateObject state = new DataStateObject();
state.workSocket = m_sock;
state.fs = new FileStream(m_filename, FileMode.Open, FileAccess.Read);
state.BytesTransfered = 0;
m_filesize = (int)state.fs.Length;
state.bufferupload = new byte[state.fs.Length];
state.fs.Read(state.bufferupload, 0, (int)state.fs.Length);
// Begin sending the data.
m_sock.BeginSend(state.bufferupload, 0, (int)state.bufferupload.Length, 0,
new AsyncCallback(SendFileCallback), state);
private void SendFileCallback(IAsyncResult ar)
// Retrieve the socket from the state object.
DataStateObject state = (DataStateObject)ar.AsyncState;
Socket sock = state.workSocket;
// Complete sending the data to the remote device.
int bytesSent = sock.EndSend(ar);
state.BytesTransfered += bytesSent;
m_endTick = Environment.TickCount;
state.BytesTransfered, m_endTick - m_startTick);