Created
August 7, 2013 15:25
-
-
Save DevJohnC/6175080 to your computer and use it in GitHub Desktop.
Socket send troubles :S
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public void Send(Message message) | |
| { | |
| if (message == null) throw new ArgumentNullException("message"); | |
| if (!IsConnected) | |
| throw new Exception("Socket not connected"); | |
| var rawMessage = message.Encode(); | |
| if (rawMessage.Length > uint.MaxValue) | |
| throw new Exception("Message too long"); | |
| var fullMessage = new byte[rawMessage.Length + 4]; | |
| var len = BitConverter.GetBytes((uint)rawMessage.Length); | |
| Buffer.BlockCopy(len, 0, fullMessage, 0, 4); | |
| Buffer.BlockCopy(rawMessage, 0, fullMessage, 4, rawMessage.Length); | |
| // wait to be signalled, _mre is signalled by default | |
| _mre.WaitOne(); | |
| _mre.Reset(); | |
| var saea = new SocketAsyncEventArgs(); | |
| saea.SetBuffer(fullMessage, 0, fullMessage.Length); | |
| saea.Completed += SendComplete; | |
| if (!_socket.SendAsync(saea)) | |
| SendComplete(_socket, saea); | |
| } | |
| private void SendComplete(object sender, SocketAsyncEventArgs socketAsyncEventArgs) | |
| { | |
| if (socketAsyncEventArgs.SocketError != SocketError.Success) | |
| Disconnect(); | |
| socketAsyncEventArgs.Dispose(); | |
| // signal that socket is ready to send again | |
| _mre.Set(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment