Exemplo n.º 1
0
        /// <summary>
        /// Starts data receive loop for the client
        /// </summary>
        public void SetupDataReceiveLoop(DataReceived callback)
        {
            _receivingData = true;
            _dataReceived  = callback;

            AsyncReceive recObject = new AsyncReceive();

            try
            {
                _socket.BeginReceive(recObject.Buffer, 0, AsyncReceive.BufferSize, SocketFlags.None,
                                     new AsyncCallback(SocketReceive), recObject);
            }
            catch (SocketException e)
            {
                Console.WriteLine("Socket error:" + e.Message);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Socket receive callback
        /// </summary>
        /// <param name="ar"></param>
        private void SocketReceive(IAsyncResult ar)
        {
            if (!_receivingData)
            {
                _socket.EndReceive(ar);

                Console.WriteLine("Unhooked async receive");
                _receivingDataEnd = true;

                return;
            }

            AsyncReceive recObject = (AsyncReceive)ar.AsyncState;

            try
            {
                int bytesRead = _socket.EndReceive(ar);

                // There's more data in the socket
                if (bytesRead > 0)
                {
                    IClientUpdate update = GetUpdate(recObject.Buffer, 0, recObject.Buffer.Length);
                    _dataReceived(this, update);

                    // Get rest of the data
                    _socket.BeginReceive(recObject.Buffer, 0, AsyncReceive.BufferSize, SocketFlags.None, new AsyncCallback(SocketReceive), recObject);
                }
                else
                {
                    // Prepare for new receive
                    recObject = new AsyncReceive();
                    _socket.BeginReceive(recObject.Buffer, 0, AsyncReceive.BufferSize, SocketFlags.None, new AsyncCallback(SocketReceive), recObject);
                }
            }
            catch (SocketException ex)
            {
                Console.WriteLine("Receive error: " + ex.Message);
                return;
            }
            catch (ObjectDisposedException ex)
            {
                Console.WriteLine("Receive error: " + ex.Message);
                return;
            }
        }