Example #1
0
        public async Task<int> ReceiveAsync(byte[] data, int offset, int size)
        {

            try
            {

                int received = await Task.Factory.FromAsync<int>(socket.BeginReceive(data, offset, size, SocketFlags.None, null, null), socket.EndReceive);

                if (received == 0)
                    throw new SocketConnectionException("Unexpected disconnect");

                return received;

            }
            catch (SocketException ex)
            {

                ConnectionErrorException connectionException = new SocketConnectionException(ex);

                if (Interlocked.Exchange(ref eventRaised, 1) == 0)
                    OnError(new ConnectionErrorEventArgs(connectionException));

                throw new SocketConnectionException(ex);

            }
            catch (ObjectDisposedException)
            {
                throw new ObjectDisposedException(GetType().Name);
            }


        }
Example #2
0
        public async Task SendAsync(byte[] data, int offset, int size)
        {

            try
            {

                int remains = size;

                while (remains > 0)
                {

                    int sent = await Task.Factory.FromAsync<int>(socket.BeginSend(data, offset + (size - remains), remains, SocketFlags.None, null, null), socket.EndSend);

                    if (sent == 0)
                        throw new SocketConnectionException("Unexpected disconnect");

                    remains -= size;

                }

            }
            catch (SocketException ex)
            {

                ConnectionErrorException connectionException = new SocketConnectionException(ex);

                if (Interlocked.Exchange(ref eventRaised, 1) == 0)
                    OnError(new ConnectionErrorEventArgs(connectionException));

                throw new SocketConnectionException(ex);

            }
            catch (ObjectDisposedException)
            {
                throw new ObjectDisposedException(GetType().Name);
            }


        }