示例#1
0
        internal void Packet(Packet packet)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info(string.Format("writing packet {0}", packet));

            if (!Encoding)
            {
                Encoding = true;
                Encoder.Encode(packet, new Parser.Encoder.CallbackImp((data) =>
                {
                    var encodedPackets = (object[])data;
                    foreach (var packet1 in encodedPackets)
                    {
                        if (packet1 is string)
                        {
                            EngineSocket.Write((string)packet1);
                        }
                        else if (packet1 is byte[])
                        {
                            EngineSocket.Write((byte[])packet1);
                        }
                    }
                    Encoding = false;
                    ProcessPacketQueue();
                }));
            }
            else
            {
                PacketBuffer.Add(packet);
            }
        }
示例#2
0
        private void OnEvent(Packet packet)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());
            //var jarr =(string) ((JValue) packet.Data).Value;
            //var job = JToken.Parse(jarr);


            //var arr = job.ToArray();

            //var args = job.Select(token => token.Value<string>()).Cast<object>().ToList();
            var args = packet.GetDataAsList();



            log.Info(string.Format("emitting event {0}", args));
            if (packet.Id >= 0)
            {
                log.Info("attaching ack callback to event");
                args.Add(new AckImp(this, packet.Id));
            }

            if (Connected)
            {
                var eventString = (string)args[0];
                args.Remove(args[0]);
                base.Emit(eventString, args.ToArray());
            }
            else
            {
                ReceiveBuffer.Enqueue(args);
            }
        }
            public void Call(object data)
            {
                var log = LogManager.GetLogger(GlobalHelper.CallerName());

                if (data is string)
                {
                    webSocket.ws.Send((string)data);
                }
                else if (data is byte[])
                {
                    var d = (byte[])data;

                    try
                    {
                        var dataString = BitConverter.ToString(d);
                        log.Info(string.Format("WriteEncodeCallback byte[] data {0}", dataString));
                    }
                    catch (Exception e)
                    {
                        log.Error(e);
                    }

                    webSocket.ws.Send(d, 0, d.Length);
                }
            }
        void ws_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info("ws_MessageReceived e.Message= " + e.Message);
            this.OnData(e.Message);
        }
        private void ws_Opened(object sender, EventArgs e)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info("ws_Opened " + ws.SupportBinary);
            this.OnOpen();
        }
示例#6
0
        public static Socket Socket(Uri uri, Options opts)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            if (opts == null)
            {
                opts = new Options();
            }

            Manager io;

            if (opts.ForceNew || !opts.Multiplex)
            {
                log.Info(string.Format("ignoring socket cache for {0}", uri.ToString()));
                io = new Manager(uri, opts);
            }
            else
            {
                var id = Url.ExtractId(uri);
                if (!Managers.ContainsKey(id))
                {
                    log.Info(string.Format("new io instance for {0}", id));
                    Managers.TryAdd(id, new Manager(uri, opts));
                }
                io = Managers[id];
            }
            return(io.Socket(uri.PathAndQuery));
        }
示例#7
0
        internal void OnHeartbeat(long timeout)
        {
            if (this.PingTimeoutTimer != null)
            {
                PingTimeoutTimer.Stop();
                PingTimeoutTimer = null;
            }

            if (timeout <= 0)
            {
                timeout = this.PingInterval + this.PingTimeout;
            }

            PingTimeoutTimer = EasyTimer.SetTimeout(() =>
            {
                var log2 = LogManager.GetLogger(GlobalHelper.CallerName());
                log2.Info("EasyTimer OnHeartbeat start");
                if (ReadyState == ReadyStateEnum.CLOSED)
                {
                    log2.Info("EasyTimer OnHeartbeat ReadyState == ReadyStateEnum.CLOSED finish");
                    return;
                }
                OnClose("ping timeout");
                log2.Info("EasyTimer OnHeartbeat finish");
            }, (int)timeout);
        }
        protected override void DoOpen()
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info("DoOpen uri =" + this.Uri());

            ws = new WebSocket4Net.WebSocket(this.Uri(), "", Cookies);
            ws.EnableAutoSendPing = false;
            if (ServerCertificate.Ignore)
            {
                var security = ws.Security;

                if (security != null)
                {
                    security.AllowUnstrustedCertificate   = true;
                    security.AllowNameMismatchCertificate = true;
                }
            }
            ws.Opened          += ws_Opened;
            ws.Closed          += ws_Closed;
            ws.MessageReceived += ws_MessageReceived;
            ws.DataReceived    += ws_DataReceived;
            ws.Error           += ws_Error;
            ws.Open();
        }
示例#9
0
        private void OnError(Exception err)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Error("error", err);
            this.EmitAll(EVENT_ERROR, err);
        }
示例#10
0
        /// <summary>
        /// Removes all listeners of the specified event.
        /// </summary>
        /// <param name="eventString">an event name</param>
        /// <returns>a reference to this object.</returns>
        public Emitter Off(string eventString)
        {
            try
            {
                List <IListener> retrievedValue;
                if (!callbacks.TryGetValue(eventString, out retrievedValue))
                {
                    var log = LogManager.GetLogger(GlobalHelper.CallerName());
                    log.Info(string.Format("Emitter.Off Could not remove {0}", eventString));
                }

                if (retrievedValue != null)
                {
                    List <IListener> outref;
                    IListener        ilistenerOutRef;
                    callbacks.TryRemove(eventString, out outref);

                    foreach (var listener in retrievedValue)
                    {
                        _onceCallbacks.TryRemove(listener, out ilistenerOutRef);
                    }
                }
            }
            catch (Exception)
            {
                this.Off();
            }

            return(this);
        }
示例#11
0
        public SocketEngine Close()
        {
            if (this.ReadyState == ReadyStateEnum.OPENING || this.ReadyState == ReadyStateEnum.OPEN)
            {
                var log = LogManager.GetLogger(GlobalHelper.CallerName());
                log.Info("Start");
                this.OnClose("forced close");

                log.Info("socket closing - telling transport to close");
                if (Transport != null)
                {
                    Transport.Close();
                }
                else
                {
                    log.Info("transport was null");
                }

                var item = TasksQueue.FirstOrDefault();
                if (item != null)
                {
                    item.CancelAll(TasksQueue);
                }
            }
            return(this);
        }
示例#12
0
            void IListener.Call(params object[] args)
            {
                object err = args[0];
                SocketEngineException error;

                if (err is Exception)
                {
                    error = new SocketEngineException("probe error", (Exception)err);
                }
                else if (err is string)
                {
                    error = new SocketEngineException("probe error: " + (string)err);
                }
                else
                {
                    error = new SocketEngineException("probe error");
                }
                error.Transport = _transport[0].Name;

                _freezeTransport.Call();

                var log = LogManager.GetLogger(GlobalHelper.CallerName());

                log.Info(string.Format("probe transport \"{0}\" failed because of error: {1}", error.Transport, err));
                _socket.Emit(EVENT_UPGRADE_ERROR, error);
            }
示例#13
0
        private void _onData(object data)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info(string.Format("polling got data {0}", data));
            var callback = new DecodePayloadCallback(this);

            if (data is string)
            {
                EngineParser.DecodePayload((string)data, callback);
            }
            else if (data is byte[])
            {
                EngineParser.DecodePayload((byte[])data, callback);
            }

            if (ReadyState != ReadyStateEnum.CLOSED)
            {
                IsPolling = false;
                log.Info("ReadyState != ReadyStateEnum.CLOSED");
                Emit(EVENT_POLL_COMPLETE);

                if (ReadyState == ReadyStateEnum.OPEN)
                {
                    Poll();
                }
                else
                {
                    log.Info(string.Format("ignoring poll - transport state {0}", ReadyState));
                }
            }
        }
示例#14
0
        void ws_DataReceived(object sender, DataReceivedEventArgs e)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info("ws_DataReceived " + e.Data);
            this.OnData(e.Data);
        }
示例#15
0
        private void OnClose(string reason)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info(string.Format("close ({0})", reason));
            Connected = false;
            Emit(EVENT_DISCONNECT, reason);
        }
            private void OnData(byte[] data)
            {
                var log = LogManager.GetLogger(GlobalHelper.CallerName());

                log.Info("OnData byte[] =" + System.Text.UTF8Encoding.UTF8.GetString(data));
                this.Emit(EVENT_DATA, data);
                this.OnSuccess();
            }
            private void OnData(string data)
            {
                var log = LogManager.GetLogger(GlobalHelper.CallerName());

                log.Info("OnData string = " + data);
                this.Emit(EVENT_DATA, data);
                this.OnSuccess();
            }
示例#18
0
        private void OnDisconnect()
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info(string.Format("server disconnect ({0})", this.Nsp));
            Destroy();
            OnClose("io server disconnect");
        }
示例#19
0
        internal void OnDrain()
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info(string.Format("OnDrain1 PrevBufferLen={0} WriteBuffer.Count={1}", PrevBufferLen, WriteBuffer.Count));


            for (int i = 0; i < this.PrevBufferLen; i++)
            {
                try
                {
                    var callback = this.CallbackBuffer[i];
                    if (callback != null)
                    {
                        callback();
                    }
                }
                catch (ArgumentOutOfRangeException)
                {
                    //ignore
                }
            }

            log.Info(string.Format("OnDrain2 PrevBufferLen={0} WriteBuffer.Count={1}", PrevBufferLen, WriteBuffer.Count));

            lock (WriteBuffer)
            {
                try
                {
                    WriteBuffer.RemoveRange(0, PrevBufferLen);
                }
                catch (ArgumentException)
                {
                    //ignore
                }
            }
            try
            {
                CallbackBuffer.RemoveRange(0, PrevBufferLen);
            }
            catch (ArgumentException)
            {
                //ignore
            }


            this.PrevBufferLen = 0;
            log.Info(string.Format("OnDrain3 PrevBufferLen={0} WriteBuffer.Count={1}", PrevBufferLen, WriteBuffer.Count));

            if (this.WriteBuffer.Count == 0)
            {
                this.Emit(EVENT_DRAIN);
            }
            else
            {
                this.Flush();
            }
        }
示例#20
0
        private void OnClose(string reason, Exception desc = null)
        {
            if (this.ReadyState == ReadyStateEnum.OPENING || this.ReadyState == ReadyStateEnum.OPEN)
            {
                var log = LogManager.GetLogger(GlobalHelper.CallerName());

                log.Info(string.Format("OnClose socket close with reason: {0}", reason));

                // clear timers
                if (this.PingIntervalTimer != null)
                {
                    this.PingIntervalTimer.Stop();
                }
                if (this.PingTimeoutTimer != null)
                {
                    this.PingTimeoutTimer.Stop();
                }


                //WriteBuffer = WriteBuffer.Clear();
                //CallbackBuffer = CallbackBuffer.Clear();
                //PrevBufferLen = 0;

                var temporaryTimer = EasyTimer.SetTimeout(() =>
                {
                    lock (WriteBuffer)
                    {
                        WriteBuffer.Clear();
                    }
                    CallbackBuffer = new List <Action>();

                    PrevBufferLen = 0;
                }, 1);

                if (this.Transport != null)
                {
                    // stop event from firing again for transport
                    this.Transport.Off(EVENT_CLOSE);

                    // ensure transport won't stay open
                    this.Transport.Close();

                    // ignore further transport communication
                    this.Transport.Off();
                }

                // set ready state
                this.ReadyState = ReadyStateEnum.CLOSED;

                // clear session id
                this.Id = null;

                // emit close events
                this.Emit(EVENT_CLOSE, reason, desc);

                temporaryTimer.Stop();
            }
        }
示例#21
0
            public void Call(params object[] args)
            {
                var log = LogManager.GetLogger(GlobalHelper.CallerName());

                log.Info("writing close packet");
                List <EnginePacket> packets = new List <EnginePacket>();

                packets.Add(new EnginePacket(EnginePacket.CLOSE));
                polling.Write(packets);
            }
示例#22
0
        private void OnOpen()
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info(string.Format("Socket OnOpen {0}", Nsp));

            if (Nsp != "/")
            {
                PacketProcess(new Packet(Parser.CONNECT));
            }
        }
示例#23
0
        protected Transport OnError(string message, Exception exception)
        {
            Exception err = new SocketEngineException(message, exception);

            this.Emit(EVENT_ERROR, err);

            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info("Transport Error: " + exception.ToString());

            return(this);
        }
示例#24
0
        void ws_Closed(object sender, EventArgs e)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info("ws_Closed");
            ws.Opened          -= ws_Opened;
            ws.Closed          -= ws_Closed;
            ws.MessageReceived -= ws_MessageReceived;
            ws.DataReceived    -= ws_DataReceived;
            ws.Error           -= ws_Error;
            this.OnClose();
        }
示例#25
0
        protected override void Write(List <EnginePacket> packets)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info("Write packets.Count = " + packets.Count);

            Writable = false;

            var callback = new SendEncodeCallback(this);

            EngineParser.EncodePayload(packets.ToArray(), callback);
        }
示例#26
0
            void IListener.Call(params object[] args)
            {
                var to = (Transport)args[0];

                if (_transport[0] != null && to.Name != _transport[0].Name)
                {
                    var log = LogManager.GetLogger(GlobalHelper.CallerName());

                    log.Info(string.Format("'{0}' works - aborting '{1}'", to.Name, _transport[0].Name));
                    _freezeTransport.Call();
                }
            }
示例#27
0
        private void OnClose(string reason)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info("OnClose");
            Cleanup();
            ReadyState = ReadyStateEnum.CLOSED;
            Emit(EVENT_CLOSE, reason);
            if (_reconnection && !SkipReconnect)
            {
                Reconnect();
            }
        }
示例#28
0
        private void OnAck(Packet packet)
        {
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info(string.Format("calling ack {0} with {1}", packet.Id, packet.Data));
            var  fn = Acks[packet.Id];
            IAck outRef;

            Acks.TryRemove(packet.Id, out outRef);

            var args = packet.GetDataAsList();

            fn.Call(args.ToArray());
        }
示例#29
0
        public Socket Close()
        {
            if (!Connected)
            {
                return(this);
            }
            var log = LogManager.GetLogger(GlobalHelper.CallerName());

            log.Info(string.Format("performing disconnect ({0})", Nsp));
            PacketProcess(new Packet(Parser.DISCONNECT));
            Destroy();
            OnClose("io client disconnect");
            return(this);
        }
示例#30
0
            public void Call(object data)
            {
                var log = LogManager.GetLogger(GlobalHelper.CallerName());

                log.Info("SendEncodeCallback data = " + data);

                var byteData = (byte[])data;

                polling.DoWrite(byteData, () =>
                {
                    polling.Writable = true;
                    polling.Emit(EVENT_DRAIN);
                });
            }