/// <summary> /// Sends data as bytes over the socket. /// </summary> /// <param name="data">The data to send.</param> private void Send(byte[] data) { if (cancelSource != null && cancelSource.IsCancellationRequested) { return; } // Begin sending the data to the remote device. AysnchronousMessage msg = new AysnchronousMessage(sock, data); sock.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), msg); sendDone.WaitOne(); sendDone.Reset(); }
/// <summary> /// The callback called once the data has been sent. /// </summary> /// <param name="res">The asynchronous result.</param> private static void SendCallback(IAsyncResult res) { // Retrieve the socket from the state object. AysnchronousMessage msg = (AysnchronousMessage)res.AsyncState; // Complete the send operation. int bytesSent = msg.sock.EndSend(res); // Send any remaing data int offset = bytesSent; int length = msg.data.Length; int remaining = length - offset; while (remaining > 0) { int additional = msg.sock.Send(msg.data, offset, remaining, 0); offset += additional; remaining -= additional; } // Signal that the message has been sent. sendDone.Set(); }