Skip to content

Instantly share code, notes, and snippets.

@DevJohnC
Created August 7, 2013 15:25
Show Gist options
  • Select an option

  • Save DevJohnC/6175080 to your computer and use it in GitHub Desktop.

Select an option

Save DevJohnC/6175080 to your computer and use it in GitHub Desktop.
Socket send troubles :S
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