//-----------------------------------------------------------------------------------------------------------------------------------------------------
 protected Stream startDownload(string url, StartCallback start, string fileName, long offset)
 {
     try
     {
         HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
         request.MaximumAutomaticRedirections = 2;
         request.AddRange(offset);
         // 发送请求并获取相应回应数据
         HttpWebResponse response = request.GetResponse() as HttpWebResponse;
         // 直到request.GetResponse()程序才开始向目标网页发送Post请求
         Stream responseStream = response.GetResponseStream();
         // 设置5秒超时
         responseStream.ReadTimeout = 5000;
         if (start != null)
         {
             // response.ContentLength只是剩余需要下载的长度,需要加上下载起始偏移才是文件的真实大小
             start(fileName, response.ContentLength + offset);
         }
         return(responseStream);
     }
     catch (Exception)
     {
         return(null);
     }
 }
示例#2
0
            /// <summary>
            /// Default constructor
            /// </summary>
            ////////////////////////////////////////////////////////////
            protected SoundRecorder() : base(IntPtr.Zero)
            {
                myStartCallback = new StartCallback(OnStart);
                myProcessCallback = new ProcessCallback(ProcessSamples);
                myStopCallback = new StopCallback(OnStop);

                SetThis(sfSoundRecorder_Create(myStartCallback, myProcessCallback, myStopCallback, IntPtr.Zero));
            }
示例#3
0
        protected virtual void ReadFile()
        {
            while (true)
            {
                var next = Dequeue();

                if (next == null)
                {
                    Thread.Sleep(100);
                    continue;
                }

                try
                {
                    if (!lastPositionDict.ContainsKey(next))
                    {
                        lastPositionDict.Add(next, 0L);
                        fileStatistics.Add(next, new TailStatistics());
                    }

                    StartCallback?.Invoke(initialLoad);
                    var totalLineCount = 0;
                    var minLineCount   = 0;
                    var clear          = false;
                    using (var reader = readerFactory.CreateReader(next))
                    {
                        var loadLastLines = LoadLastLines();
                        if (initialLoad && loadLastLines >= 0 && lastPositionDict[next] == 0)
                        {
                            totalLineCount = reader.CountLines();
                            minLineCount   = totalLineCount > loadLastLines ? totalLineCount - loadLastLines : 0;
                        }

                        var lastPosition = lastPositionDict[next];

                        if (lastPosition > reader.Length)
                        {
                            lastPositionDict[next] = lastPosition = 0L;
                            fileStatistics[next].Reset();
                            initialLoad = true;
                            StartCallback?.Invoke(initialLoad);
                            clear = true;
                        }

                        reader.Seek(lastPosition);
                        ReadLines(reader, next, minLineCount, clear);
                        lastPositionDict[next] = reader.Position;
                    }

                    FinishCallback?.Invoke(initialLoad, fileStatistics[next]);
                    initialLoad = false;
                }
                catch (Exception ex)
                {
                    ExceptionCallback?.Invoke(ex);
                }
            }
        }
示例#4
0
        ////////////////////////////////////////////////////////////
        /// <summary>
        /// Default constructor
        /// </summary>
        ////////////////////////////////////////////////////////////
        public SoundRecorder() :
            base(IntPtr.Zero)
        {
            myStartCallback   = new StartCallback(OnStart);
            myProcessCallback = new ProcessCallback(ProcessSamples);
            myStopCallback    = new StopCallback(OnStop);

            CPointer = sfSoundRecorder_create(myStartCallback, myProcessCallback, myStopCallback, IntPtr.Zero);
        }
示例#5
0
            ////////////////////////////////////////////////////////////
            /// <summary>
            /// Default constructor
            /// </summary>
            ////////////////////////////////////////////////////////////
            public SoundRecorder() :
                base(IntPtr.Zero)
            {
                myStartCallback = new StartCallback(OnStart);
                myProcessCallback = new ProcessCallback(ProcessSamples);
                myStopCallback = new StopCallback(OnStop);

                CPointer = sfSoundRecorder_create(myStartCallback, myProcessCallback, myStopCallback, IntPtr.Zero);
            }
示例#6
0
            ////////////////////////////////////////////////////////////
            /// <summary>
            /// Default constructor
            /// </summary>
            ////////////////////////////////////////////////////////////
            public SoundRecorder() :
                base(IntPtr.Zero)
            {
                myStartCallback   = new StartCallback(OnStart);
                myProcessCallback = new ProcessCallback(ProcessSamples);
                myStopCallback    = new StopCallback(OnStop);

                SetThis(sfSoundRecorder_Create(myStartCallback, myProcessCallback, myStopCallback, IntPtr.Zero));
            }
示例#7
0
 public void ClearCallback()
 {
     if (StartDelayChanged != null)
     {
         foreach (Delegate d in StartDelayChanged.GetInvocationList())
         {
             StartDelayChanged -= (EventHandler)d;
         }
     }
     if (DurationChanged != null)
     {
         foreach (Delegate d in DurationChanged.GetInvocationList())
         {
             DurationChanged -= (EventHandler)d;
         }
     }
     if (PositionRequest != null)
     {
         foreach (Delegate d in PositionRequest.GetInvocationList())
         {
             PositionRequest -= (EventHandler)d;
         }
     }
     if (StartCallback != null)
     {
         foreach (Delegate d in StartCallback.GetInvocationList())
         {
             StartCallback -= (EventHandler)d;
         }
     }
     if (StopCallback != null)
     {
         foreach (Delegate d in StopCallback.GetInvocationList())
         {
             StopCallback -= (EventHandler)d;
         }
     }
     if (NextCallback != null)
     {
         foreach (Delegate d in NextCallback.GetInvocationList())
         {
             NextCallback -= (EventHandler)d;
         }
     }
     if (PrevCallback != null)
     {
         foreach (Delegate d in PrevCallback.GetInvocationList())
         {
             PrevCallback -= (EventHandler)d;
         }
     }
 }
    public void upload(string fullURL, string fileName, string uploadPath, StartCallback start, FinishCallback finish)
    {
        mUploadListLock.waitForUnlock();
        DownloadInfo info = new DownloadInfo();

        info.mURL            = StringUtility.strReplaceAll(fullURL, " ", "%20");
        info.mFileName       = fileName;
        info.mUploadPath     = uploadPath;
        info.mStartCallback  = start;
        info.mFinishCallback = finish;
        mUploadList.Add(info);
        mUploadListLock.unlock();
    }
示例#9
0
        public void Start()
        {
            _IsDone = false;
            StartCallback?.Invoke(this, new EventArgs());
            if (_IsDone)
            {
                return;
            }

            _IsPlaying = true;
            synchronizationContext.Post((o) => {
                timer1.Enabled = true;
            }, null);
        }
示例#10
0
        public void start(StartCallback callback)
        {
            try
            {
                lock(this)
                {
                    //
                    // The connection might already be closed if the communicator was destroyed.
                    //
                    if(_state >= StateClosed)
                    {
                        Debug.Assert(_exception != null);
                        throw _exception;
                    }

                    if(!initialize(IceInternal.SocketOperation.None) || !validate(IceInternal.SocketOperation.None))
                    {
                        _startCallback = callback;
                        return;
                    }

                    //
                    // We start out in holding state.
                    //
                    setState(StateHolding);
                }
            }
            catch(LocalException ex)
            {
                exception(ex);
                callback.connectionStartFailed(this, _exception);
                return;
            }

            callback.connectionStartCompleted(this);
        }
示例#11
0
        public void start(StartCallback callback)
        {
            try
            {
                _m.Lock();
                try
                {
                    //
                    // The connection might already be closed if the communicator was destroyed.
                    //
                    if(_state >= StateClosed)
                    {
                        Debug.Assert(_exception != null);
                        throw _exception;
                    }

                    if(!initialize(IceInternal.SocketOperation.None) || !validate(IceInternal.SocketOperation.None))
                    {
                        if(callback != null)
                        {
                            _startCallback = callback;
                            return;
                        }

                        //
                        // Wait for the connection to be validated.
                        //
                        while(_state <= StateNotValidated)
                        {
                            _m.Wait();
                        }

                        if(_state >= StateClosing)
                        {
                            Debug.Assert(_exception != null);
                            throw _exception;
                        }
                    }

                    //
                    // We start out in holding state.
                    //
                    setState(StateHolding);
                }
                finally
                {
                    _m.Unlock();
                }
            }
            catch(LocalException ex)
            {
                exception(ex);
                if(callback != null)
                {
                    callback.connectionStartFailed(this, _exception);
                    return;
                }
                else
                {
                    waitUntilFinished();
                    throw;
                }
            }

            if(callback != null)
            {
                callback.connectionStartCompleted(this);
            }
        }
示例#12
0
        private void dispatch(StartCallback startCB, Queue<OutgoingMessage> sentCBs, MessageInfo info)
        {
            //
            // Notify the factory that the connection establishment and
            // validation has completed.
            //
            if(startCB != null)
            {
                startCB.connectionStartCompleted(this);
            }

            //
            // Notify AMI calls that the message was sent.
            //
            if(sentCBs != null)
            {
                foreach(OutgoingMessage m in sentCBs)
                {
                    if(m.sentCallback != null)
                    {
                        m.outAsync.sent__(m.sentCallback);
                    }
                    if(m.replyOutAsync != null)
                    {
                        m.replyOutAsync.finished__();
                    }
                }
            }

            //
            // Asynchronous replies must be handled outside the thread
            // synchronization, so that nested calls are possible.
            //
            if(info.outAsync != null)
            {
                info.outAsync.finished__();
            }

            if(info.invokeNum > 0)
            {
                //
                // Method invocation (or multiple invocations for batch messages)
                // must be done outside the thread synchronization, so that nested
                // calls are possible.
                //
                invokeAll(info.stream, info.invokeNum, info.requestId, info.compress, info.servantManager,
                          info.adapter);
            }

            //
            // Decrease dispatch count.
            //
            if(sentCBs != null || info.outAsync != null)
            {
                _m.Lock();
                try
                {
                    if(--_dispatchCount == 0)
                    {
                        //
                        // Only initiate shutdown if not already done. It
                        // might have already been done if the sent callback
                        // or AMI callback was dispatched when the connection
                        // was already in the closing state.
                        //
                        if(_state == StateClosing && !_shutdownInitiated)
                        {
                            try
                            {
                                initiateShutdown();
                            }
                            catch(Ice.LocalException ex)
                            {
                                setState(StateClosed, ex);
                            }
                        }
                        else if(_state == StateFinished)
                        {
                            _reaper.add(this, _observer);
                        }
                        _m.NotifyAll();
                    }
                }
                finally
                {
                    _m.Unlock();
                }
            }
        }
 public void Start(StartCallback callback)
 {
     mSpeechIdentifier.Start(callback);
 }
示例#14
0
 public static void StartPreview(this IntPtr camera, StartCallback startCallback, FrameCallback frameCallback, IntPtr context)
 {
 }
示例#15
0
 public static extern void install_callbacks(
     ShouldHandleCallback should_handle_callback,
     EnqueueCalculationCallback enqueue_calculation_callback,
     StartCallback start_callback,
     NotifierNotificationHandle.CalculationCompleteCallback calculation_complete_callback);
示例#16
0
        public static AnimationBehaviour CreateAnimation(this MonoBehaviour monoBehaviour, AnimationEaseType easeType,
                                                         float duration,
                                                         float delay = 0f, string name = null, StartCallback startCallback = null, UpdateCallback updateCallback = null,
                                                         CancelCallback cancelCallback = null,
                                                         DoneCallback doneCallback     = null, FinishCallback finishCallback = null, bool single = false,
                                                         bool considerTimeScale        = false, object data = null, bool inverse = false)
        {
            var ease = AnimationHelper.EaseTypeToFunction(easeType);

            return(CreateAnimation(monoBehaviour, ease, duration, delay, name, startCallback, updateCallback, cancelCallback, doneCallback, finishCallback, single, considerTimeScale, data, inverse));
        }
示例#17
0
        public static AnimationBehaviour CreateAnimation(this MonoBehaviour monoBehaviour, IAnimationEase ease, float duration,
                                                         float delay = 0f, string name = null, StartCallback startCallback = null, UpdateCallback updateCallback             = null, CancelCallback cancelCallback = null,
                                                         DoneCallback doneCallback = null, FinishCallback finishCallback = null, bool single = false, bool considerTimeScale = false, object data                  = null, bool inverse = false)
        {
            if (single)
            {
                if (string.IsNullOrEmpty(name))
                {
                    Debug.Log("Animation can just be single if its name is not empty neither null.");
                }
                else
                {
                    CancelAnimations(monoBehaviour, name);
                }
            }

            var gameObject = monoBehaviour.gameObject;
            var anim       = gameObject.AddComponent <AnimationBehaviour>();

            anim.Delay             = delay;
            anim.Name              = name;
            anim.Ease              = ease;
            anim.StartCallback     = startCallback;
            anim.UpdateCallback    = updateCallback;
            anim.FinishCallback    = finishCallback;
            anim.Duration          = duration;
            anim.DoneCallback      = doneCallback;
            anim.CancelCallback    = cancelCallback;
            anim.ConsiderTimeScale = considerTimeScale;
            anim.Data              = data ?? monoBehaviour;
            anim.Inverse           = inverse;
            anim.Start();

            return(anim);
        }
示例#18
0
        public static AnimationBehaviour CreateAnimation <TEase>(this MonoBehaviour monoBehaviour, float duration,
                                                                 float delay = 0f, string name = null, StartCallback startCallback = null, UpdateCallback updateCallback = null,
                                                                 CancelCallback cancelCallback = null, DoneCallback doneCallback = null, FinishCallback finishCallback = null,
                                                                 bool single = false, bool considerTimeScale = true, object data = null, bool inverse = false) where TEase : IAnimationEase, new()
        {
            var ease = new TEase();

            return(CreateAnimation(monoBehaviour, ease, duration, delay, name, startCallback, updateCallback, cancelCallback, doneCallback, finishCallback, single, considerTimeScale, data, inverse));
        }
示例#19
0
 public void Start(StartCallback callback)
 {
     mSpeechEnroller.Start(callback);
 }
示例#20
0
 public static extern void RegisterCoreCallbacks(StartCallback startCallback, PreviewCallback previewCallback, PhotoCallback photoCallback);
    public void download(string fullURL, string fileName, long offset, DownloadingCallback downloading, TimeoutCallback timeout, StartCallback start, FinishCallback finish)
    {
        mDownloadListLock.waitForUnlock();
        DownloadInfo info = new DownloadInfo();

        // 下载地址里需要将空格替换为%20
        info.mURL                 = StringUtility.strReplaceAll(fullURL, " ", "%20");
        info.mFileName            = fileName;
        info.mDownloadingCallback = downloading;
        info.mStartCallback       = start;
        info.mFinishCallback      = finish;
        info.mTimeoutCallback     = timeout;
        info.mDownloadOffset      = offset;
        mDownloadList.Add(info);
        mDownloadListLock.unlock();
    }
示例#22
0
 static extern IntPtr sfSoundRecorder_create(StartCallback OnStart, ProcessCallback OnProcess, StopCallback OnStop, IntPtr UserData);
示例#23
0
文件: Runtime.cs 项目: vfqd/piranesi
 void Start() => StartCallback?.Invoke();
示例#24
0
 static extern IntPtr sfSoundRecorder_Create(StartCallback OnStart, ProcessCallback OnProcess, StopCallback OnStop, IntPtr UserData);
示例#25
0
        private void dispatch(StartCallback startCB, Queue<OutgoingMessage> sentCBs, MessageInfo info)
        {
            int dispatchedCount = 0;

            //
            // Notify the factory that the connection establishment and
            // validation has completed.
            //
            if(startCB != null)
            {
                startCB.connectionStartCompleted(this);
                ++dispatchedCount;
            }

            //
            // Notify AMI calls that the message was sent.
            //
            if(sentCBs != null)
            {
                foreach(OutgoingMessage m in sentCBs)
                {
                    if(m.sentCallback != null)
                    {
                        m.outAsync.invokeSent(m.sentCallback);
                    }
                    if(m.receivedReply)
                    {
                        IceInternal.OutgoingAsync outAsync = (IceInternal.OutgoingAsync)m.outAsync;
                        Ice.AsyncCallback cb = outAsync.completed();
                        if(cb != null)
                        {
                            outAsync.invokeCompleted(cb);
                        }
                    }
                }
                ++dispatchedCount;
            }

            //
            // Asynchronous replies must be handled outside the thread
            // synchronization, so that nested calls are possible.
            //
            if(info.outAsync != null)
            {
                info.outAsync.invokeCompleted(info.completedCallback);
                ++dispatchedCount;
            }

            if(info.heartbeatCallback != null)
            {
                try
                {
                    info.heartbeatCallback.heartbeat(this);
                }
                catch(System.Exception ex)
                {
                    _logger.error("connection callback exception:\n" + ex + '\n' + _desc);
                }
                ++dispatchedCount;
            }

            //
            // Method invocation (or multiple invocations for batch messages)
            // must be done outside the thread synchronization, so that nested
            // calls are possible.
            //
            if(info.invokeNum > 0)
            {
                invokeAll(info.stream, info.invokeNum, info.requestId, info.compress, info.servantManager,
                          info.adapter);

                //
                // Don't increase dispatchedCount, the dispatch count is
                // decreased when the incoming reply is sent.
                //
            }

            //
            // Decrease dispatch count.
            //
            if(dispatchedCount > 0)
            {
                lock(this)
                {
                    _dispatchCount -= dispatchedCount;
                    if(_dispatchCount == 0)
                    {
                        //
                        // Only initiate shutdown if not already done. It
                        // might have already been done if the sent callback
                        // or AMI callback was dispatched when the connection
                        // was already in the closing state.
                        //
                        if(_state == StateClosing)
                        {
                            try
                            {
                                initiateShutdown();
                            }
                            catch(Ice.LocalException ex)
                            {
                                setState(StateClosed, ex);
                            }
                        }
                        else if(_state == StateFinished)
                        {
                            reap();
                        }
                        System.Threading.Monitor.PulseAll(this);
                    }
                }
            }
        }
示例#26
0
 private static extern IntPtr VidyoVirtualWindowShareConstructNative(IntPtr id, IntPtr windowName, IntPtr applicationName, StartCallback onStart, ReconfigureCallback onReconfigure, StopCallback onStop);
示例#27
0
        public override void message(ref IceInternal.ThreadPoolCurrent current)
        {
            StartCallback startCB = null;
            Queue<OutgoingMessage> sentCBs = null;
            MessageInfo info = new MessageInfo();

            IceInternal.ThreadPoolMessage msg = new IceInternal.ThreadPoolMessage(_m);
            _m.Lock();
            try
            {
                if(!msg.startIOScope(ref current))
                {
                    return;
                }

                if(_state >= StateClosed)
                {
                    return;
                }

                try
                {
                    unscheduleTimeout(current.operation);
                    if((current.operation & IceInternal.SocketOperation.Write) != 0 && !_writeStream.isEmpty())
                    {
                        if(_writeStream.getBuffer().b.hasRemaining() && !_transceiver.write(_writeStream.getBuffer()))
                        {
                            Debug.Assert(!_writeStream.isEmpty());
                            scheduleTimeout(IceInternal.SocketOperation.Write, _endpoint.timeout());
                            return;
                        }
                        Debug.Assert(!_writeStream.getBuffer().b.hasRemaining());
                    }
                    if((current.operation & IceInternal.SocketOperation.Read) != 0 && !_readStream.isEmpty())
                    {
                        if(_readHeader) // Read header if necessary.
                        {
                            if(_readStream.getBuffer().b.hasRemaining() && !_transceiver.read(_readStream.getBuffer()))
                            {
                                return;
                            }
                            Debug.Assert(!_readStream.getBuffer().b.hasRemaining());
                            _readHeader = true;

                            int pos = _readStream.pos();
                            if(pos < IceInternal.Protocol.headerSize)
                            {
                                //
                                // This situation is possible for small UDP packets.
                                //
                                throw new Ice.IllegalMessageSizeException();
                            }

                            _readStream.pos(0);
                            byte[] m = new byte[4];
                            m[0] = _readStream.readByte();
                            m[1] = _readStream.readByte();
                            m[2] = _readStream.readByte();
                            m[3] = _readStream.readByte();
                            if(m[0] != IceInternal.Protocol.magic[0] || m[1] != IceInternal.Protocol.magic[1] ||
                               m[2] != IceInternal.Protocol.magic[2] || m[3] != IceInternal.Protocol.magic[3])
                            {
                                Ice.BadMagicException ex = new Ice.BadMagicException();
                                ex.badMagic = m;
                                throw ex;
                            }

                            byte pMajor = _readStream.readByte();
                            byte pMinor = _readStream.readByte();
                            if(pMajor != IceInternal.Protocol.protocolMajor ||
                               pMinor > IceInternal.Protocol.protocolMinor)
                            {
                                Ice.UnsupportedProtocolException e = new Ice.UnsupportedProtocolException();
                                e.badMajor = pMajor < 0 ? pMajor + 255 : pMajor;
                                e.badMinor = pMinor < 0 ? pMinor + 255 : pMinor;
                                e.major = IceInternal.Protocol.protocolMajor;
                                e.minor = IceInternal.Protocol.protocolMinor;
                                throw e;
                            }

                            byte eMajor = _readStream.readByte();
                            byte eMinor = _readStream.readByte();
                            if(eMajor != IceInternal.Protocol.encodingMajor ||
                               eMinor > IceInternal.Protocol.encodingMinor)
                            {
                                Ice.UnsupportedEncodingException e = new Ice.UnsupportedEncodingException();
                                e.badMajor = eMajor < 0 ? eMajor + 255 : eMajor;
                                e.badMinor = eMinor < 0 ? eMinor + 255 : eMinor;
                                e.major = IceInternal.Protocol.encodingMajor;
                                e.minor = IceInternal.Protocol.encodingMinor;
                                throw e;
                            }

                            _readStream.readByte(); // messageType
                            _readStream.readByte(); // compress
                            int size = _readStream.readInt();
                            if(size < IceInternal.Protocol.headerSize)
                            {
                                throw new Ice.IllegalMessageSizeException();
                            }
                            if(size > _instance.messageSizeMax())
                            {
                                IceInternal.Ex.throwMemoryLimitException(size, _instance.messageSizeMax());
                            }
                            if(size > _readStream.size())
                            {
                                _readStream.resize(size, true);
                            }
                            _readStream.pos(pos);
                        }

                        if(_readStream.pos() != _readStream.size())
                        {
                            if(_endpoint.datagram())
                            {
                                throw new Ice.DatagramLimitException(); // The message was truncated.
                            }
                            else
                            {
                                if(_readStream.getBuffer().b.hasRemaining() &&
                                   !_transceiver.read(_readStream.getBuffer()))
                                {
                                    Debug.Assert(!_readStream.isEmpty());
                                    scheduleTimeout(IceInternal.SocketOperation.Read, _endpoint.timeout());
                                    return;
                                }
                                Debug.Assert(!_readStream.getBuffer().b.hasRemaining());
                            }
                        }
                    }

                    if(_state <= StateNotValidated)
                    {
                        if(_state == StateNotInitialized && !initialize(current.operation))
                        {
                            return;
                        }

                        if(_state <= StateNotValidated && !validate(current.operation))
                        {
                            return;
                        }

                        _threadPool.unregister(this, current.operation);

                        //
                        // We start out in holding state.
                        //
                        setState(StateHolding);
                        startCB = _startCallback;
                        _startCallback = null;
                    }
                    else
                    {
                        Debug.Assert(_state <= StateClosing);

                        if((current.operation & IceInternal.SocketOperation.Write) != 0)
                        {
                            sentCBs = sendNextMessage();
                        }

                        if((current.operation & IceInternal.SocketOperation.Read) != 0)
                        {
                            parseMessage(new IceInternal.BasicStream(_instance), ref info);
                        }
                    }

                    //
                    // We increment the dispatch count to prevent the
                    // communicator destruction during the callback.
                    //
                    if(sentCBs != null || info.outAsync != null)
                    {
                        ++_dispatchCount;
                    }

                    if(_acmTimeout > 0)
                    {
                        _acmAbsoluteTimeoutMillis = IceInternal.Time.currentMonotonicTimeMillis() + _acmTimeout * 1000;
                    }

                    if(startCB == null && sentCBs == null && info.invokeNum == 0 && info.outAsync == null)
                    {
                        return; // Nothing to dispatch.
                    }

                    msg.completed(ref current);
                }
                catch(DatagramLimitException) // Expected.
                {
                    if(_warnUdp)
                    {
                        _logger.warning("maximum datagram size of " + _readStream.pos() + " exceeded");
                    }
                    _readStream.resize(IceInternal.Protocol.headerSize, true);
                    _readStream.pos(0);
                    _readHeader = true;
                    return;
                }
                catch(SocketException ex)
                {
                    setState(StateClosed, ex);
                    return;
                }
                catch(LocalException ex)
                {
                    if(_endpoint.datagram())
                    {
                        if(_warn)
                        {
                            String s = "datagram connection exception:\n" + ex + '\n' + _desc;
                            _logger.warning(s);
                        }
                        _readStream.resize(IceInternal.Protocol.headerSize, true);
                        _readStream.pos(0);
                        _readHeader = true;
                    }
                    else
                    {
                        setState(StateClosed, ex);
                    }
                    return;
                }
                finally
                {
                    msg.finishIOScope(ref current);
                }

                //
                // Unlike C++/Java, this method is called from an IO thread of the .NET thread
                // pool or from the communicator async IO thread. While it's fine to handle the
                // non-blocking activity of the connection from these threads, the dispatching
                // of the message must be taken care of by the Ice thread pool.
                //
                IceInternal.ThreadPoolCurrent c = current;
                _threadPool.execute(
                    delegate()
                    {
                        if(_dispatcher != null)
                        {
                            try
                            {
                                _dispatcher(delegate()
                                            {
                                                dispatch(startCB, sentCBs, info);
                                            },
                                            this);
                            }
                            catch(System.Exception ex)
                            {
                                if(_instance.initializationData().properties.getPropertyAsIntWithDefault(
                                       "Ice.Warn.Dispatch", 1) > 1)
                                {
                                    warning("dispatch exception", ex);
                                }
                            }
                        }
                        else
                        {
                            dispatch(startCB, sentCBs, info);
                        }
                        msg.destroy(ref c);
                    });
            }
            finally
            {
                _m.Unlock();
            }
        }
示例#28
0
 public CreateWalkerModelInteraction(StartCallback start)
 {
     Start = start;
 }
示例#29
0
        private void finish()
        {
            if(!_initialized)
            {
                if(_instance.traceLevels().network >= 2)
                {
                    StringBuilder s = new StringBuilder("failed to ");
                    s.Append(_connector != null ? "establish" : "accept");
                    s.Append(" ");
                    s.Append(_endpoint.protocol());
                    s.Append(" connection\n");
                    s.Append(ToString());
                    s.Append("\n");
                    s.Append(_exception);
                    _instance.initializationData().logger.trace(_instance.traceLevels().networkCat, s.ToString());
                }
            }
            else
            {
                if(_instance.traceLevels().network >= 1)
                {
                    StringBuilder s = new StringBuilder("closed ");
                    s.Append(_endpoint.protocol());
                    s.Append(" connection\n");
                    s.Append(ToString());

                    //
                    // Trace the cause of unexpected connection closures
                    //
                    if(!(_exception is CloseConnectionException ||
                         _exception is ForcedCloseConnectionException ||
                         _exception is ConnectionTimeoutException ||
                         _exception is CommunicatorDestroyedException ||
                         _exception is ObjectAdapterDeactivatedException))
                    {
                        s.Append("\n");
                        s.Append(_exception);
                    }

                    _instance.initializationData().logger.trace(_instance.traceLevels().networkCat, s.ToString());
                }
            }

            if(_startCallback != null)
            {
                _startCallback.connectionStartFailed(this, _exception);
                _startCallback = null;
            }

            if(_sendStreams.Count > 0)
            {
                if(!_writeStream.isEmpty())
                {
                    //
                    // Return the stream to the outgoing call. This is important for
                    // retriable AMI calls which are not marshalled again.
                    //
                    OutgoingMessage message = _sendStreams.First.Value;
                    _writeStream.swap(message.stream);

                    //
                    // The current message might be sent but not yet removed from _sendStreams. If
                    // the response has been received in the meantime, we remove the message from
                    // _sendStreams to not call finished on a message which is already done.
                    //
                    if(message.isSent || message.receivedReply)
                    {
                        if(message.sent() && message.invokeSent)
                        {
                            message.outAsync.invokeSent();
                        }
                        if(message.receivedReply)
                        {
                            IceInternal.OutgoingAsync outAsync = (IceInternal.OutgoingAsync)message.outAsync;
                            if(outAsync.response())
                            {
                                outAsync.invokeResponse();
                            }
                        }
                        _sendStreams.RemoveFirst();
                    }
                }

                foreach (OutgoingMessage o in _sendStreams)
                {
                    o.completed(_exception);
                    if(o.requestId > 0) // Make sure finished isn't called twice.
                    {
                        _asyncRequests.Remove(o.requestId);
                    }
                }
                _sendStreams.Clear(); // Must be cleared before _requests because of Outgoing* references in OutgoingMessage
            }

            foreach(IceInternal.OutgoingAsyncBase o in _asyncRequests.Values)
            {
                if(o.exception(_exception))
                {
                    o.invokeException();
                }
            }
            _asyncRequests.Clear();

            //
            // Don't wait to be reaped to reclaim memory allocated by read/write streams.
            //
            _writeStream.clear();
            _writeStream.getBuffer().clear();
            _readStream.clear();
            _readStream.getBuffer().clear();
            _incomingCache = null;

            if(_closeCallback != null)
            {
                try
                {
                    _closeCallback(this);
                }
                catch(System.Exception ex)
                {
                    _logger.error("connection callback exception:\n" + ex + '\n' + _desc);
                }
                _closeCallback = null;
            }

            _heartbeatCallback = null;

            //
            // This must be done last as this will cause waitUntilFinished() to return (and communicator
            // objects such as the timer might be destroyed too).
            //
            lock(this)
            {
                setState(StateFinished);

                if(_dispatchCount == 0)
                {
                    reap();
                }
            }
        }
示例#30
0
        public override void message(ref IceInternal.ThreadPoolCurrent current)
        {
            StartCallback startCB = null;
            Queue<OutgoingMessage> sentCBs = null;
            MessageInfo info = new MessageInfo();
            int dispatchCount = 0;

            IceInternal.ThreadPoolMessage msg = new IceInternal.ThreadPoolMessage(this);
            try
            {
                lock(this)
                {
                    if(!msg.startIOScope(ref current))
                    {
                        return;
                    }

                    if(_state >= StateClosed)
                    {
                        return;
                    }

                    int readyOp = current.operation;
                    try
                    {
                        unscheduleTimeout(current.operation);

                        int writeOp = IceInternal.SocketOperation.None;
                        int readOp = IceInternal.SocketOperation.None;
                        if((readyOp & IceInternal.SocketOperation.Write) != 0)
                        {
                            if(_observer != null)
                            {
                                observerStartWrite(_writeStream.getBuffer());
                            }
                            writeOp = write(_writeStream.getBuffer());
                            if(_observer != null && (writeOp & IceInternal.SocketOperation.Write) == 0)
                            {
                                observerFinishWrite(_writeStream.getBuffer());
                            }
                        }

                        while((readyOp & IceInternal.SocketOperation.Read) != 0)
                        {
                            IceInternal.Buffer buf = _readStream.getBuffer();

                            if(_observer != null && !_readHeader)
                            {
                                observerStartRead(buf);
                            }

                            readOp = read(buf);
                            if((readOp & IceInternal.SocketOperation.Read) != 0)
                            {
                                break;
                            }
                            if(_observer != null && !_readHeader)
                            {
                                Debug.Assert(!buf.b.hasRemaining());
                                observerFinishRead(buf);
                            }

                            if(_readHeader) // Read header if necessary.
                            {
                                _readHeader = false;

                                if(_observer != null)
                                {
                                    _observer.receivedBytes(IceInternal.Protocol.headerSize);
                                }

                                int pos = _readStream.pos();
                                if(pos < IceInternal.Protocol.headerSize)
                                {
                                    //
                                    // This situation is possible for small UDP packets.
                                    //
                                    throw new Ice.IllegalMessageSizeException();
                                }

                                _readStream.pos(0);
                                byte[] m = new byte[4];
                                m[0] = _readStream.readByte();
                                m[1] = _readStream.readByte();
                                m[2] = _readStream.readByte();
                                m[3] = _readStream.readByte();
                                if(m[0] != IceInternal.Protocol.magic[0] || m[1] != IceInternal.Protocol.magic[1] ||
                                   m[2] != IceInternal.Protocol.magic[2] || m[3] != IceInternal.Protocol.magic[3])
                                {
                                    Ice.BadMagicException ex = new Ice.BadMagicException();
                                    ex.badMagic = m;
                                    throw ex;
                                }

                                ProtocolVersion pv  = new ProtocolVersion();
                                pv.read__(_readStream);
                                IceInternal.Protocol.checkSupportedProtocol(pv);
                                EncodingVersion ev = new EncodingVersion();
                                ev.read__(_readStream);
                                IceInternal.Protocol.checkSupportedProtocolEncoding(ev);

                                _readStream.readByte(); // messageType
                                _readStream.readByte(); // compress
                                int size = _readStream.readInt();
                                if(size < IceInternal.Protocol.headerSize)
                                {
                                    throw new Ice.IllegalMessageSizeException();
                                }
                                if(size > _messageSizeMax)
                                {
                                    IceInternal.Ex.throwMemoryLimitException(size, _messageSizeMax);
                                }
                                if(size > _readStream.size())
                                {
                                    _readStream.resize(size);
                                }
                                _readStream.pos(pos);
                            }

                            if(buf.b.hasRemaining())
                            {
                                if(_endpoint.datagram())
                                {
                                    throw new Ice.DatagramLimitException(); // The message was truncated.
                                }
                                continue;
                            }
                            break;
                        }

                        int newOp = readOp | writeOp;
                        readyOp &= ~newOp;
                        Debug.Assert(readyOp != 0 || newOp != 0);

                        if(_state <= StateNotValidated)
                        {
                            if(newOp != 0)
                            {
                                //
                                // Wait for all the transceiver conditions to be
                                // satisfied before continuing.
                                //
                                scheduleTimeout(newOp);
                                _threadPool.update(this, current.operation, newOp);
                                return;
                            }

                            if(_state == StateNotInitialized && !initialize(current.operation))
                            {
                                return;
                            }

                            if(_state <= StateNotValidated && !validate(current.operation))
                            {
                                return;
                            }

                            _threadPool.unregister(this, current.operation);

                            //
                            // We start out in holding state.
                            //
                            setState(StateHolding);
                            if(_startCallback != null)
                            {
                                startCB = _startCallback;
                                _startCallback = null;
                                if(startCB != null)
                                {
                                    ++dispatchCount;
                                }
                            }
                        }
                        else
                        {
                            Debug.Assert(_state <= StateClosingPending);

                            //
                            // We parse messages first, if we receive a close
                            // connection message we won't send more messages.
                            //
                            if((readyOp & IceInternal.SocketOperation.Read) != 0)
                            {
                                newOp |= parseMessage(ref info);
                                dispatchCount += info.messageDispatchCount;
                            }

                            if((readyOp & IceInternal.SocketOperation.Write) != 0)
                            {
                                newOp |= sendNextMessage(out sentCBs);
                                if(sentCBs != null)
                                {
                                    ++dispatchCount;
                                }
                            }

                            if(_state < StateClosed)
                            {
                                scheduleTimeout(newOp);
                                _threadPool.update(this, current.operation, newOp);
                            }
                        }

                        if(_acmLastActivity > -1)
                        {
                            _acmLastActivity = IceInternal.Time.currentMonotonicTimeMillis();
                        }

                        if(dispatchCount == 0)
                        {
                            return; // Nothing to dispatch we're done!
                        }

                        _dispatchCount += dispatchCount;

                        msg.completed(ref current);
                    }
                    catch(DatagramLimitException) // Expected.
                    {
                        if(_warnUdp)
                        {
                            _logger.warning("maximum datagram size of " + _readStream.pos() + " exceeded");
                        }
                        _readStream.resize(IceInternal.Protocol.headerSize);
                        _readStream.pos(0);
                        _readHeader = true;
                        return;
                    }
                    catch(SocketException ex)
                    {
                        setState(StateClosed, ex);
                        return;
                    }
                    catch(LocalException ex)
                    {
                        if(_endpoint.datagram())
                        {
                            if(_warn)
                            {
                                String s = "datagram connection exception:\n" + ex + '\n' + _desc;
                                _logger.warning(s);
                            }
                            _readStream.resize(IceInternal.Protocol.headerSize);
                            _readStream.pos(0);
                            _readHeader = true;
                        }
                        else
                        {
                            setState(StateClosed, ex);
                        }
                        return;
                    }

                    IceInternal.ThreadPoolCurrent c = current;
                    _threadPool.dispatch(() =>
                    {
                        dispatch(startCB, sentCBs, info);
                        msg.destroy(ref c);
                    }, this);
                }
            }
            finally
            {
                msg.finishIOScope(ref current);
            }
        }
 public void Start(StartCallback callback)
 {
     mSpeechVerifier.Start(callback);
 }
示例#32
0
        private void finish()
        {
            if(_startCallback != null)
            {
                _startCallback.connectionStartFailed(this, _exception);
                _startCallback = null;
            }

            if(_sendStreams.Count > 0)
            {
                Debug.Assert(!_writeStream.isEmpty());

                //
                // Return the stream to the outgoing call. This is important for
                // retriable AMI calls which are not marshalled again.
                //
                OutgoingMessage message = _sendStreams.Peek();
                _writeStream.swap(message.stream);

                //
                // The current message might be sent but not yet removed from _sendStreams. If
                // the response has been received in the meantime, we remove the message from
                // _sendStreams to not call finished on a message which is already done.
                //
                if(message.requestId > 0 &&
                   (message.@out != null && !_requests.ContainsKey(message.requestId) ||
                    message.outAsync != null && !_asyncRequests.ContainsKey(message.requestId)))
                {
                    if(message.sent(this, true))
                    {
                        Debug.Assert(message.outAsync != null);
                        message.outAsync.sent__(message.sentCallback);
                    }
                    _sendStreams.Dequeue();
                }

                foreach(OutgoingMessage m in _sendStreams)
                {
                    m.finished(_exception);
                    if(m.requestId > 0) // Make sure finished isn't called twice.
                    {
                        if(m.@out != null)
                        {
                            _requests.Remove(m.requestId);
                        }
                        else
                        {
                            _asyncRequests.Remove(m.requestId);
                        }
                    }
                }
                _sendStreams.Clear();
            }

            foreach(IceInternal.Outgoing o in _requests.Values)
            {
                o.finished(_exception, true);
            }
            _requests.Clear();

            foreach(IceInternal.OutgoingAsync o in _asyncRequests.Values)
            {
                o.finished__(_exception, true);
            }
            _asyncRequests.Clear();

            //
            // This must be done last as this will cause waitUntilFinished() to return (and communicator
            // objects such as the timer might be destroyed too).
            //
            _m.Lock();
            try
            {
                setState(StateFinished);
                if(_dispatchCount == 0)
                {
                    _reaper.add(this);
                }
            }
            finally
            {
                _m.Unlock();
            }
        }