/// <summary> /// QueueMessage prepares a Message object containing our data to send and queues this Message object in the OutboundMessageQueue. /// </summary> /// <remarks></remarks> public void SendToClient(object obj, Socket argClient) { // serialize the Packet into a stream of bytes which is suitable for sending with the Socket System.Runtime.Serialization.Formatters.Binary.BinaryFormatter mSerializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (System.IO.MemoryStream mSerializerStream = new System.IO.MemoryStream()) { mSerializer.Serialize(mSerializerStream, obj); // get the serialized Packet bytes byte[] mPacketBytes = mSerializerStream.GetBuffer(); // convert the size into a byte array byte[] mSizeBytes = BitConverter.GetBytes(mPacketBytes.Length + 4); // create the async state object which we can pass between async methods SocketGlobals.AsyncSendState mState = new SocketGlobals.AsyncSendState(argClient); // resize the BytesToSend array to fit both the mSizeBytes and the mPacketBytes // TODO: ReDim mState.BytesToSend(mPacketBytes.Length + mSizeBytes.Length - 1) Array.Resize(ref mState.BytesToSend, mPacketBytes.Length + mSizeBytes.Length); // copy the mSizeBytes and mPacketBytes to the BytesToSend array Buffer.BlockCopy(mSizeBytes, 0, mState.BytesToSend, 0, mSizeBytes.Length); Buffer.BlockCopy(mPacketBytes, 0, mState.BytesToSend, mSizeBytes.Length, mPacketBytes.Length); Array.Clear(mSizeBytes, 0, mSizeBytes.Length); Array.Clear(mPacketBytes, 0, mPacketBytes.Length); Console.Write(""); // queue the Message Console.WriteLine("Server (SendToClient): NextOffset: {0}; NextLength: {1}", mState.NextOffset(), mState.NextLength()); argClient.BeginSend(mState.BytesToSend, mState.NextOffset(), mState.NextLength(), SocketFlags.None, new AsyncCallback(MessagePartSent), mState); } }
public void MessagePartSent(IAsyncResult ar) { // get the async state object which was returned by the async beginsend method SocketGlobals.AsyncSendState mState = (SocketGlobals.AsyncSendState)ar.AsyncState; try { int numBytesSent = 0; // call the EndSend method which will succeed or throw an error depending on if we are still connected numBytesSent = mState.Socket.EndSend(ar); // increment the total amount of bytes processed so far mState.Progress += numBytesSent; // determine if we havent' sent all the data for this Packet yet if (mState.NextLength() > 0) { // we need to send more data mState.Socket.BeginSend(mState.BytesToSend, mState.NextOffset(), mState.NextLength(), SocketFlags.None, new AsyncCallback(MessagePartSent), mState); } else { Console.WriteLine("Server MessagePartSent completed. Clearing stuff..."); Array.Clear(mState.BytesToSend, 0, mState.BytesToSend.Length); //mState.Socket.Dispose(); // x?x? n mState = null; } // at this point, the EndSend succeeded and we are ready to send something else! } catch (Exception ex) { myLogger.Log("DataSent error: " + ex.Message); } }