void OnConnected(BestHTTP.SocketIO.Socket socket, BestHTTP.SocketIO.Packet packet, object[] args)
 {
     IsConnected = true;
     if (Connected != null)
     {
         Connected(this, null);
     }
 }
 void OnConnected(BestHTTP.SocketIO.Socket socket, BestHTTP.SocketIO.Packet packet, object[] args)
 {
     Debug.Log("Connected to socket server");
 }
示例#3
0
        /// <summary>
        /// Called when a "connect" event received to the root namespace
        /// </summary>
        private void OnTransportOpen(Socket socket, Packet packet, params object[] args)
        {
            // If this is not the root namespace, then we send a connect message to the server
            if (this.Namespace != "/")
                (Manager as IManager).SendPacket(new Packet(TransportEventTypes.Message, SocketIOEventTypes.Connect, this.Namespace, string.Empty));

            // and we are no open
            IsOpen = true;
        }
示例#4
0
        public Socket EmitAck(Packet originalPacket, params object[] args)
        {
            if (originalPacket == null)
                throw new ArgumentNullException("originalPacket == null!");

            if (/*originalPacket.Id == 0 ||*/
                (originalPacket.SocketIOEvent != SocketIOEventTypes.Event && originalPacket.SocketIOEvent != SocketIOEventTypes.BinaryEvent))
                throw new ArgumentException("Wrong packet - you can't send an Ack for a packet with id == 0 and SocketIOEvent != Event or SocketIOEvent != BinaryEvent!");

            arguments.Clear();
            if (args != null && args.Length > 0)
                arguments.AddRange(args);

            string payload = null;
            try
            {
                payload = Manager.Encoder.Encode(arguments);
            }
            catch (Exception ex)
            {
                (this as ISocket).EmitError(SocketIOErrors.Internal, "Error while encoding payload: " + ex.Message + " " + ex.StackTrace);

                return this;
            }

            if (payload == null)
                throw new ArgumentException("Encoding the arguments to JSON failed!");

            Packet packet = new Packet(TransportEventTypes.Message,
                                       originalPacket.SocketIOEvent == SocketIOEventTypes.Event ? SocketIOEventTypes.Ack : SocketIOEventTypes.BinaryAck,
                                       this.Namespace,
                                       payload,
                                       0,
                                       originalPacket.Id);

            (Manager as IManager).SendPacket(packet);

            return this;
        }
示例#5
0
        /// <summary>
        /// Last call of the OnPacket chain(Transport -> Manager -> Socket), we will dispatch the event if there is any callback
        /// </summary>
        void ISocket.OnPacket(Packet packet)
        {
            // Some preprocessing of the the packet
            switch(packet.SocketIOEvent)
            {
                case SocketIOEventTypes.Disconnect:
                    if (IsOpen)
                    {
                        IsOpen = false;
                        EventCallbacks.Call(EventNames.GetNameFor(SocketIOEventTypes.Disconnect), packet);
                        Disconnect();
                    }
                    break;

                // Create an Error object from the server-sent json string
                case SocketIOEventTypes.Error:
                    bool success = false;
                    var errDict = JSON.Json.Decode(packet.Payload, ref success) as Dictionary<string, object>;
                    if (success)
                    {
                        Error err = new Error((SocketIOErrors)Convert.ToInt32(errDict["code"]),
                                                                              errDict["message"] as string);

                        EventCallbacks.Call(EventNames.GetNameFor(SocketIOEventTypes.Error), packet, err);

                        return;
                    }
                    break;
            }

            // Dispatch the event to all subscriber
            EventCallbacks.Call(packet);

            // call Ack callbacks
            if ((packet.SocketIOEvent == SocketIOEventTypes.Ack || packet.SocketIOEvent == SocketIOEventTypes.BinaryAck) && AckCallbacks != null)
            {
                SocketIOAckCallback ackCallback = null;
                if (AckCallbacks.TryGetValue(packet.Id, out ackCallback) && 
                    ackCallback != null)
                {
                    try
                    {
                        ackCallback(this, packet, packet.Decode(Manager.Encoder));
                    }
                    catch (Exception ex)
                    {
                        HTTPManager.Logger.Exception("Socket", "ackCallback", ex);
                    }
                }

                AckCallbacks.Remove(packet.Id);
            }
        }
示例#6
0
        public Socket Emit(string eventName, SocketIOAckCallback callback, params object[] args)
        {
            bool blackListed = EventNames.IsBlacklisted(eventName);
            if (blackListed)
                throw new ArgumentException("Blacklisted event: " + eventName);

            arguments.Clear();
            arguments.Add(eventName);

            // Find and swap any binary data(byte[]) to a placeholder string.
            // Server side these will be swapped back.
            List<byte[]> attachments = null;
            if (args != null && args.Length > 0)
            {
                int idx = 0;
                for (int i = 0; i < args.Length; ++i)
                {
                    byte[] binData = args[i] as byte[];
                    if (binData != null)
                    {
                        if (attachments == null)
                            attachments = new List<byte[]>();

                        Dictionary<string, object> placeholderObj = new Dictionary<string, object>(2);
                        placeholderObj.Add(Packet.Placeholder, true);
                        placeholderObj.Add("num", idx++);

                        arguments.Add(placeholderObj);

                        attachments.Add(binData);
                    }
                    else
                        arguments.Add(args[i]);
                }
            }

            string payload = null;

            try
            {
                payload = Manager.Encoder.Encode(arguments);
            }
            catch(Exception ex)
            {
                (this as ISocket).EmitError(SocketIOErrors.Internal, "Error while encoding payload: " + ex.Message + " " + ex.StackTrace);

                return this;
            }

            // We don't use it further in this function, so we can clear it to not hold any unwanted reference.
            arguments.Clear();

            if (payload == null)
                throw new ArgumentException("Encoding the arguments to JSON failed!");

            int id = 0;

            if (callback != null)
            {
                id = Manager.NextAckId;

                if (AckCallbacks == null)
                    AckCallbacks = new Dictionary<int, SocketIOAckCallback>();

                AckCallbacks[id] = callback;
            }

            Packet packet = new Packet(TransportEventTypes.Message,
                                       attachments == null ? SocketIOEventTypes.Event : SocketIOEventTypes.BinaryEvent,
                                       this.Namespace,
                                       payload,
                                       0,
                                       id);

            if (attachments != null)
                packet.Attachments = attachments; // This will set the AttachmentCount property too.

            (Manager as IManager).SendPacket(packet);

            return this;
        }
示例#7
0
        /// <summary>
        /// Disconnects this socket/namespace.
        /// </summary>
        void ISocket.Disconnect(bool remove)
        {
            // Send a disconnect packet to the server
            if (IsOpen)
            {
                Packet packet = new Packet(TransportEventTypes.Message, SocketIOEventTypes.Disconnect, this.Namespace, string.Empty);
                (Manager as IManager).SendPacket(packet);

                // IsOpen must be false, becouse in the OnPacket preprocessing the packet would call this function again
                IsOpen = false;
                (this as ISocket).OnPacket(packet);
            }

            if (AckCallbacks != null)
                AckCallbacks.Clear();

            if (remove)
            {
                EventCallbacks.Clear();

                (Manager as IManager).Remove(this);
            }
        }
        /// <summary>
        /// Will clone this packet to an identical packet instance.
        /// </summary>
        internal Packet Clone()
        {
            Packet packet = new Packet(this.TransportEvent, this.SocketIOEvent, this.Namespace, this.Payload, 0, this.Id);
            packet.EventName = this.EventName;
            packet.AttachmentCount = this.AttachmentCount;
            packet.attachments = this.attachments;

            return packet;
        }
示例#9
0
        /// <summary>
        /// Called from the currently operating Transport. Will pass forward to the Socket that has to call the callbacks.
        /// </summary>
        void IManager.OnPacket(Packet packet)
        {
            if (State == States.Closed)
                return;

            switch(packet.TransportEvent)
            {
                case TransportEventTypes.Ping:
                    (this as IManager).SendPacket(new Packet(TransportEventTypes.Pong, SocketIOEventTypes.Unknown, "/", string.Empty));
                    break;

                case TransportEventTypes.Pong:
                    LastPongReceived = DateTime.UtcNow;
                    break;
            }

            Socket socket = null;
            if (Namespaces.TryGetValue(packet.Namespace, out socket))
                (socket as ISocket).OnPacket(packet);
            else
                HTTPManager.Logger.Warning("SocketManager", "Namespace \"" + packet.Namespace + "\" not found!");
        }
示例#10
0
        /// <summary>
        /// Internal function that called from the Socket class. It will send out the packet instantly, or if no transport is available it will store
        /// the packet in the OfflinePackets list.
        /// </summary>
        void IManager.SendPacket(Packet packet)
        {
            ITransport trans = SelectTransport();

            if (trans != null)
            {
                try
                {
                    trans.Send(packet);
                }
                catch(Exception ex)
                {
                    (this as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
                }
            }
            else
            {
                if (OfflinePackets == null)
                    OfflinePackets = new List<Packet>();

                // The same packet can be sent through multiple Sockets. 
                OfflinePackets.Add(packet.Clone());
            }
        }