public void Send(Byte[] data) { lock (sendQueueLock) { sendQueue.AddRange(BitConverter.GetBytes(data.Length)); sendQueue.AddRange(data); } if (!hasNetworkCycleStarted && helper.IsConnected(clientSocket)) { hasNetworkCycleStarted = true; Byte[] outgoing = null; lock (sendQueueLock) { outgoing = sendQueue.ToArray(); sendQueue.Clear(); } helper.BeginSend(outgoing, new AsyncCallback(sendCallback), clientSocket); } }
protected void receiveCallback(IAsyncResult ar) { var socket = (Socket)ar.AsyncState; Int32 receivedBytes = 0; try { receivedBytes = helper.EndReceive(ar, socket); } catch (SocketException) { // socket has become diconnected. OnDisconnected(instanceNodeId); } catch (ObjectDisposedException) { // socket/thread is being shut down. return; } // if nothing was received, the socket either closed, or some other problem, so return. if (receivedBytes == 0) { return; } OnReceivedData(this, buffer); // lock the send queue, build a byte array of the data and clear the queue. Byte[] outgoing = null; lock (sendQueueLock) { outgoing = sendQueue.ToArray(); sendQueue.Clear(); } // send a response try { helper.BeginSend(outgoing, new AsyncCallback(sendCallback), socket); } catch (SocketException) { // socket has become diconnected. OnDisconnected(instanceNodeId); } catch (ObjectDisposedException) { // socket/thread is being shut down. (no need to log this) } }