void DoOpen()
    {
        if (socket == null)
        {
            string URL = "ws://" + SettingStat.ServerURL;
            Quobject.SocketIoClientDotNet.Client.IO.Options OPT = new Quobject.SocketIoClientDotNet.Client.IO.Options();
            //OPT.Reconnection = true;
            //OPT.ForceNew = false;
            //OPT.AutoConnect = true;
            //OPT.Timeout = 3000;
            OPT.Transports   = ImmutableList.Create(new string[] { WebSocket.NAME, Polling.NAME });
            OPT.Reconnection = true;

            socket = IO.Socket(URL, OPT);
            socket.On(Socket.EVENT_CONNECT, () => {
                Debug.Log("Socket connected");
            });
            socket.On("chat", (data) => {
                string str = data.ToString();

                ChatData chat     = JsonConvert.DeserializeObject <ChatData>(str);
                string strChatLog = chat.msg;  //receive the signal from server which is triggered by localhost3000

                order = strChatLog;
            });
            socket.On(Socket.EVENT_DISCONNECT, () => {
                Debug.Log("user PC disconnected");
            });
        }
    }
Пример #2
0
        protected IO.Options CreateOptionsSecure()
        {
            var log = LogManager.GetLogger(Global.CallerName());

            var config = ConfigBase.Load();
            var options = new IO.Options();
            options.Port = config.server.ssl_port;
            options.Hostname = config.server.hostname;
            log.Info("Please add to your hosts file: 127.0.0.1 " + options.Hostname);
            options.Secure = true;
            options.IgnoreServerCertificateValidation = true;
            return options;
        }
Пример #3
0
        protected IO.Options CreateOptions()
        {
            var log = LogManager.GetLogger(Global.CallerName());


            var config = ConfigBase.Load();
            var options = new IO.Options();
            options.Port = config.server.port;
            options.Hostname = config.server.hostname;
            options.ForceNew = true;
            log.Info("Please add to your hosts file: 127.0.0.1 " + options.Hostname);

            return options;
        }
Пример #4
0
        public LinkIO connect(Action listener)
        {
            IO.Options opts = new IO.Options();
            Dictionary<String, String> query = new Dictionary<String, String>();
            query.Add("user", user);

            if(id != "")
                query.Add("id", id);

            opts.Query = query;
            opts.AutoConnect = false;

            socket = IO.Socket("http://" + serverIP, opts);

            socket.On("users", (e) =>
            {
                if (userInRoomChangedListener != null)
                    userInRoomChangedListener.Invoke(((JArray) e).ToObject<List<User>>());
            });

            socket.On(Socket.EVENT_CONNECT, () =>
            {
                connected = true;
                listener.Invoke();
            });

            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                connected = false;
            });

            socket.On("event", (Object o) =>
            {
                JObject evt = (JObject) o;
                String eventName = (String) evt.SelectToken("type");
                if (eventListeners.ContainsKey(eventName))
                {
                    eventListeners[eventName].Invoke(new Event(evt));
                }                        


            });

            socket.Connect();

            return this;
        }
        private void SetupMeshbluConnection()
        {
            var opts = new IO.Options();

            opts.Port = _config.MeshbluPort;
            opts.ForceNew = true;
            opts.Secure = true;
            opts.IgnoreServerCertificateValidation = true;

            _socket = Quobject.SocketIoClientDotNet.Client.IO.Socket(_config.MeshbluUrl, opts);
        }
Пример #6
0
        public LinkIO connect(Action<LinkIO> listener)
        {
            IO.Options opts = new IO.Options();
            Dictionary<String, String> query = new Dictionary<String, String>();
            if(mail != "")
				query.Add("mail", mail);

            if (password != "")
                query.Add("password", password);
			
			query.Add("api_key", api_key);
			
            opts.Query = query;
            opts.AutoConnect = false;
            opts.Transports = ImmutableList.Create<string>(WebSocket.NAME, Polling.NAME);

            socket = IO.Socket("http://" + serverIP, opts);

            socket.On("users", (e) =>
            {
                List<User> users = ((JArray)e).ToObject<List<User>>();
                if (users.Count > usersInRoom.Count)
                {
                    foreach(User user1 in users)
                    {
                        bool found = false;
                        foreach(User user2 in usersInRoom)
                        {
                            if (user1.ID == user2.ID)
                                found = true;
                        }
                        if (!found)
                            userJoinListener.Invoke(user1);
                    }
                }
                else
                {
                    foreach (User user1 in usersInRoom)
                    {
                        bool found = false;
                        foreach (User user2 in users)
                        {
                            if (user1.ID == user2.ID)
                                found = true;
                        }

                        if (!found)
                            userLeftListener.Invoke(user1);
                    }
                }

                usersInRoom = users;
            });
			
			socket.On("error", (Object o) =>
            {
                if (errorHandler != null)
                {
                    string message = (string)((JValue)o);
                    message = message.Replace("\"", "");

                    switch (((string)((JValue)o)).Replace("\"", ""))
                    {
                        case "ACCOUNT ERROR":
                            errorHandler.Invoke(new AccountNotFoundException("Email does not match any account in API."));
                            break;
                        case "PASSWORD ERROR":
                            errorHandler.Invoke(new WrongPasswordException("Password does not match the given Email."));
                            break;
                        case "API_KEY ERROR":
                        default:
                            errorHandler.Invoke(new WrongAPIKeyException("The application does not match with an API key."));
                            break;
                    }
                }
            });

            socket.On("info", (Object o) =>
            {
                JObject evt = (JObject)o;

                currentUser = new User()
                {
                    Name = (String)evt.SelectToken("name"),
                    FirstName = (String)evt.SelectToken("firstname"),
                    Mail = (String)evt.SelectToken("mail"),
                    ID = (String)evt.SelectToken("id"),
                    Role = (String)evt.SelectToken("role")
                };

                Task.Run(() =>
                {
                    connected = true;
                    listener.Invoke(this);
                });
            });

            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                connected = false;
            });

            socket.On("event", (Object o) =>
            {
                JObject evt = (JObject)o;
                String eventName = (String)evt.SelectToken("type");
                if (eventListeners.ContainsKey(eventName))
                {
                    Task.Run(() =>
                    {
                        eventListeners[eventName].Invoke(new Event(evt, cSharpBinarySerializer));
                    });
                }


            });
            
            socket.Connect();

            return this;
        }
Пример #7
0
        private static List<SniperInfo> GetSniperInfoFrom_pokezz(ISession session, List<PokemonId> pokemonIds)
        {
            var options = new IO.Options();
            options.Transports = Quobject.Collections.Immutable.ImmutableList.Create<string>("websocket");

            var socket = IO.Socket("http://pokezz.com", options);

            var hasError = false;

            ManualResetEventSlim waitforbroadcast = new ManualResetEventSlim(false);

            List<PokemonLocation_pokezz> pokemons = new List<PokemonLocation_pokezz>();

            socket.On("pokemons", (msg) =>
            {
                socket.Close();
                JArray data = JArray.FromObject(msg);

                foreach (var pokeToken in data.Children())
                {
                    var Token = pokeToken.ToString().Replace(" M", "Male").Replace(" F", "Female").Replace("Farfetch'd", "Farfetchd").Replace("Mr.Maleime", "MrMime");
                    pokemons.Add(JToken.Parse(Token).ToObject<PokemonLocation_pokezz>());
                }

                waitforbroadcast.Set();
            });

            socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_ERROR, () =>
            {
                socket.Close();
                hasError = true;
                waitforbroadcast.Set();
            });

            socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_CONNECT_ERROR, () =>
            {
                socket.Close();
                hasError = true;
                waitforbroadcast.Set();
            });

            waitforbroadcast.Wait();
            if (!hasError)
            {
                foreach (var pokemon in pokemons)
                {
                    var SnipInfo = new SniperInfo();
                    SnipInfo.Id = pokemon.name;
                    SnipInfo.Latitude = pokemon.lat;
                    SnipInfo.Longitude = pokemon.lng;
                    SnipInfo.TimeStampAdded = DateTime.Now;
                    SnipInfo.ExpirationTimestamp = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Math.Round(pokemon.time / 1000d)).ToLocalTime();
                    SnipInfo.IV = pokemon._iv;
                    if (pokemon.verified || !session.LogicSettings.GetOnlyVerifiedSniperInfoFromPokezz)
                        SnipeLocations.Add(SnipInfo);
                }

                var locationsToSnipe = SnipeLocations?.Where(q =>
                    (!session.LogicSettings.UseTransferIvForSnipe ||
                    (q.IV == 0 && !session.LogicSettings.SnipeIgnoreUnknownIv) ||
                    (q.IV >= session.Inventory.GetPokemonTransferFilter(q.Id).KeepMinIvPercentage)) &&
                    !LocsVisited.Contains(new PokemonLocation(q.Latitude, q.Longitude))
                    && !(q.ExpirationTimestamp != default(DateTime) &&
                    q.ExpirationTimestamp > new DateTime(2016) &&
                    // make absolutely sure that the server sent a correct datetime
                    q.ExpirationTimestamp < DateTime.Now) &&
                    (q.Id == PokemonId.Missingno || pokemonIds.Contains(q.Id))).ToList() ??
                    new List<SniperInfo>();

                return locationsToSnipe.OrderBy(q => q.ExpirationTimestamp).ToList();
            }
            else
            {
                session.EventDispatcher.Send(new ErrorEvent {Message = "(Pokezz.com) Connection Error"});
                return null;
            }
        }
Пример #8
0
        public void connectSocket()
        {
            if (this.TOKEN != null)
                {
                    try
                    {
                        Dictionary<string, string> _author = new Dictionary<string, string>();
                        _author.Add("token", this.TOKEN);
                        IO.Options _option = new IO.Options();
                        //_option.Timeout = 5000;
                        _option.Query = _author;
                        _option.ForceNew = true;
                        _option.Reconnection = true;
                        _option.ReconnectionDelay = 500;

                        mSocket = IO.Socket(HOSTNAME, _option);
                        mSocket.On(Socket.EVENT_CONNECT, () =>
                        {
                            Dispatcher dispatcher = Deployment.Current.Dispatcher;
                            dispatcher.BeginInvoke(() =>
                            {
                              //  MessageBox.Show("OK");
                            });
                            Debug.WriteLine("OK");
                        });
                        mSocket.On(Socket.EVENT_CONNECT_ERROR, onConnectError);
                        mSocket.On(Socket.EVENT_CONNECT_TIMEOUT, onConnectTimeout);
                        mSocket.On(Socket.EVENT_ERROR, () =>
                        {
                            Dispatcher dispatcher = Deployment.Current.Dispatcher;
                            dispatcher.BeginInvoke(() =>
                            {
                               // MessageBox.Show("ERROR");
                                mSocket.Connect();
                                mSocket.Open();
                            });
                        });
                        mSocket.On(Constant.SOCKET_EVENT_JOIN, onJoinRoom);
                        mSocket.On(Constant.SOCKET_EVENT_ADD, onAddUser);
                        mSocket.On(Constant.SOCKET_EVENT_LEAVE, onLeaveRoom);
                        mSocket.On(Constant.SOCKET_EVENT_CHANGE_ROOM_TITLE, onChangeRoomTitle);
                        mSocket.On(Constant.SOCKET_EVENT_CHAT, (data) => {
                            Debug.WriteLine(data.ToString());
                            Dispatcher dispatcher = Deployment.Current.Dispatcher;
                            dispatcher.BeginInvoke(() =>
                            {
                                String result = data.ToString();
                                ChatResponse resultObject = JsonConvert.DeserializeObject<ChatResponse>(result);
                                if(resultObject.data.message.type == 2)
                                {
                                    App.ViewModel.Items.Add(new ViewModels.ItemViewModel() { SenderID = resultObject.data.sender._id, CreateAt = resultObject.data.sequence, MessageText = resultObject.data.message.message, Avatar = new Uri(resultObject.data.sender.avatar), Type = resultObject.data.message.type, thumbnail = new Uri(resultObject.data.message.file.thumbnail, UriKind.RelativeOrAbsolute) });
                                }
                                else
                                {
                                    App.ViewModel.Items.Add(new ViewModels.ItemViewModel() { SenderID = resultObject.data.sender._id, CreateAt = resultObject.data.sequence, MessageText = resultObject.data.message.message, Avatar = new Uri(resultObject.data.sender.avatar), Type = resultObject.data.message.type });
                                }

                                if(resultObject.data.sender._id != App._userid)
                                {
                                    var stream = Application.GetResourceStream(new Uri(@"Assets/Audio/recieve.wav", UriKind.RelativeOrAbsolute));
                                    var effect = SoundEffect.FromStream(stream.Stream);
                                    var soundInstance = effect.CreateInstance();

                                    FrameworkDispatcher.Update();
                                    soundInstance.Play();
                                    App._reuserid = resultObject.data.sender._id;
                                    ToastPrompt tost = new ToastPrompt()
                                    {
                                        Title = resultObject.data.sender.username,
                                        Message = resultObject.data.message.message,
                                    };
                                    tost.Tap += tosk_Tap;
                                    tost.Show();
                                }
                            });
                        });
                        mSocket.Connect();
                    }
                catch(Exception e)
                    {
                        Debug.WriteLine("IO exception  " + e.Message);
                        //mSocket.Close();
                       // mSocket.Open();
                    }
                }
                else
                {
                    Debug.WriteLine("No token found!");
                }
        }
Пример #9
0
        private static List<SniperInfo> GetSniperInfoFrom_pokezz(ISession session, List<PokemonId> pokemonIds)
        {
            var options = new IO.Options();
            options.Transports = Quobject.Collections.Immutable.ImmutableList.Create<string>("websocket");

            var socket = IO.Socket("http://pokezz.com", options);

            var hasError = true;

            ManualResetEventSlim waitforbroadcast = new ManualResetEventSlim(false);

            List<PokemonLocation_pokezz> pokemons = new List<PokemonLocation_pokezz>();

            socket.On("a", (msg) =>
            {
                hasError = false;
                socket.Close();
                string[] pokemonDefinitions = ((String)msg).Split('~');
                foreach (var pokemonDefinition in pokemonDefinitions)
                {
                    try
                    {
                        string[] pokemonDefinitionElements = pokemonDefinition.Split('|');
                        PokemonLocation_pokezz pokezzElement = new PokemonLocation_pokezz();
                        pokezzElement.name = (PokemonId)Convert.ToInt32(pokemonDefinitionElements[0], CultureInfo.InvariantCulture);
                        pokezzElement.lat = Convert.ToDouble(pokemonDefinitionElements[1], CultureInfo.InvariantCulture);
                        pokezzElement.lng = Convert.ToDouble(pokemonDefinitionElements[2], CultureInfo.InvariantCulture);
                        pokezzElement.time = Convert.ToDouble(pokemonDefinitionElements[3], CultureInfo.InvariantCulture);
                        pokezzElement.verified = (pokemonDefinitionElements[4] == "0") ? false : true;
                        pokezzElement.iv = pokemonDefinitionElements[5];

                        pokemons.Add(pokezzElement);
                    }
                    catch(Exception)
                    {
                        // Just in case Pokezz changes their implementation, let's catch the error and set the error flag.
                        hasError = true;
                    }
                }
                
                waitforbroadcast.Set();
            });

            socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_ERROR, () =>
            {
                socket.Close();
                waitforbroadcast.Set();
            });

            socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_CONNECT_ERROR, () =>
            {
                socket.Close();
                waitforbroadcast.Set();
            });

            waitforbroadcast.Wait(5000); // Wait a maximum of 5 seconds for Pokezz to respond.
            socket.Close();
            if (!hasError)
            {
                foreach (var pokemon in pokemons)
                {
                    var SnipInfo = new SniperInfo();
                    SnipInfo.Id = pokemon.name;
                    SnipInfo.Latitude = pokemon.lat;
                    SnipInfo.Longitude = pokemon.lng;
                    SnipInfo.TimeStampAdded = DateTime.Now;
                    SnipInfo.ExpirationTimestamp = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(pokemon.time).ToLocalTime();
                    SnipInfo.IV = pokemon._iv;
                    if (pokemon.verified || !session.LogicSettings.GetOnlyVerifiedSniperInfoFromPokezz)
                        SnipeLocations.Add(SnipInfo);
                }

                var locationsToSnipe = SnipeLocations?.Where(q =>
                    (!session.LogicSettings.UseTransferIvForSnipe ||
                    (q.IV == 0 && !session.LogicSettings.SnipeIgnoreUnknownIv) ||
                    (q.IV >= session.Inventory.GetPokemonTransferFilter(q.Id).KeepMinIvPercentage)) &&
                    !LocsVisited.Contains(new PokemonLocation(q.Latitude, q.Longitude))
                    && !(q.ExpirationTimestamp != default(DateTime) &&
                    q.ExpirationTimestamp > new DateTime(2016) &&
                    // make absolutely sure that the server sent a correct datetime
                    q.ExpirationTimestamp < DateTime.Now) &&
                    (q.Id == PokemonId.Missingno || pokemonIds.Contains(q.Id))).ToList() ??
                    new List<SniperInfo>();

                return locationsToSnipe.OrderBy(q => q.ExpirationTimestamp).ToList();
            }
            else
            {
                session.EventDispatcher.Send(new ErrorEvent {Message = "(Pokezz.com) Connection Error"});
                return null;
            }
        }