Пример #1
0
        //Обработка запроса на регистрацию
        private void HandleRegistration(RemoteClient client, RegistrationMessage registrationMessage)
        {
            //проверяем, есть ли в базе пользователь с таким имемен
            var userWithSomwName = storage.Find(U => U.Name == registrationMessage.UserName);

            //Если пользователь  с таким именем есть в базе
            if (userWithSomwName != null)
            {
                //Сообщаем клиенту, что такое имя занято
                client.Send(new Response(StatusCode.UserNameBusy));
                //И больше ничего не делаем
                return;
            }
            //Имя пользователя не занято, создаем новый аккаунт
            User user = new User
            {
                Name     = registrationMessage.UserName,
                Password = registrationMessage.UserPassword
            };

            //Сохраняем его в хранилище
            storage.RegisterUser(user);
            //И привызываем его к соединению, по которому пришел запрос на регистрацию
            client.UserView = user;
            //Отправяем клиенту инфу о том что он успешно зарегистрировался
            client.Send(Response.GoodResponse);
        }
Пример #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="routePath">Call method path, ex:className.method</param>
        /// <param name="param"></param>
        /// <param name="callback"></param>
        public void Call(string routePath, RequestParam param, Action <RemotePackage> callback)
        {
            int msgId = Interlocked.Increment(ref _msgId);

            param["MsgId"]    = msgId;
            param["route"]    = routePath;
            param["Sid"]      = _sessionId;
            param["Uid"]      = _userId;
            param["ActionId"] = 0;
            param["ssid"]     = _proxySessionId;
            param["isproxy"]  = true;
            param["proxyId"]  = _proxyId;
            string post = string.Format("d={0}", HttpUtility.UrlEncode(param.ToPostString()));

            if (_client.IsSocket)
            {
                post = "?" + post;
            }
            var responsePack = new RemotePackage {
                MsgId = _msgId, RouteName = routePath
            };

            responsePack.Callback += callback;
            PutToWaitQueue(responsePack);
            _client.Send(post);
        }
Пример #3
0
        private void ClientTreatment_OnMessageParsed(NetworkElement arg1, ProtocolJsonContent arg2)
        {
            var hooker = HookManager <T> .Instance[LocalClient.localIp.Port];

            if (hooker is null)
            {
                logger.Error("no proxy found");
                return;
            }

            if (ClientTreatment.Informations is MessageBuffer informations)
            {
                hooker.Proxy.LAST_GLOBAL_INSTANCE_ID = informations.InstanceId;
            }

            uint instance_id = hooker.Proxy.LAST_GLOBAL_INSTANCE_ID + hooker.Proxy.FAKE_MESSAGE_SENT;
            StartupConfiguration configuration = Configurations.ConfigurationManager.Instance.Startup;

            if (configuration.show_message)
            {
                logger.Info($"[client {RemoteClient.remoteIp}] {arg1.BasicString()}");
                if (configuration.show_message_content)
                {
                    logger.Info($"{arg2}");
                }
            }

            HandlerManager.Instance.Handle(arg1.protocolID, LocalClient, RemoteClient, arg2);
            RemoteClient.Send(ClientTreatment.Informations.ReWriteInstanceId(instance_id));
        }
Пример #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="routePath">Call method path, ex:className.method</param>
        /// <param name="param"></param>
        /// <param name="callback"></param>
        public void Call(string routePath, RequestParam param, Action <RemotePackage> callback)
        {
            _msgId++;
            param["MsgId"]    = _msgId;
            param["route"]    = routePath;
            param["Sid"]      = _sessionId;
            param["Uid"]      = _userId;
            param["ActionId"] = 0;
            param["ssid"]     = _proxySessionId;
            param["isproxy"]  = true;
            param["proxyId"]  = _proxyId;
            string post = param.ToPostString();

            if (_client.IsSocket)
            {
                post = "?" + post;
            }
            var responsePack = new RemotePackage {
                MsgId = _msgId, RouteName = routePath
            };

            responsePack.Callback += callback;
            PutToWaitQueue(responsePack);
            _client.Send(post);
        }
Пример #5
0
			// Token: 0x060000EA RID: 234 RVA: 0x0000275F File Offset: 0x0000095F
			public void Execute(RemoteClient cl)
			{
				if (cl != null)
				{
					cl.Send(this);
				}
			}
Пример #6
0
    static void Main(string[] args)
    {
        FieldInfo assetManagerField = typeof(GameEnvironment).GetField("assetManager", BindingFlags.Static | BindingFlags.NonPublic);

        assetManagerField.SetValue(null, new EmptyAssetManager());

        LocalServer  server = new LocalServer();
        RemoteClient rc     = new RemoteClient(server);

        //JoinServerEvent jse = new JoinServerEvent();
        //jse.clientName = "test";
        LevelUpdatedEvent lue = new LevelUpdatedEvent();

        lue.updatedLevel = server.Level;

        rc.Send(lue);


        IFormatter formatter = new BinaryFormatter();
        Stream     stream    = new FileStream("MyTestFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
        Event      obj       = (Event)formatter.Deserialize(stream);

        stream.Close();



        startTime = DateTime.UtcNow;

        playingState = new PlayingState();

        Timer timer = new Timer(tick, null, 0, (int)(1000f / 60f));

        Console.Read();
    }
Пример #7
0
 public void WhenISendAnEchoRequestWithValueThroughTheRemoteClientOnTheThread(int value, int threadId)
 {
     Tasks.Add(Task.Factory.StartNew(() =>
     {
         var response = RemoteClient.Send <EchoRequest, EchoResponse>(new EchoRequest(value.ToString()));
         ResponseByThread.GetOrAdd(threadId, i => response);
     }));
 }
Пример #8
0
        //Обработка запрососа на логин
        private void HandleLogin(RemoteClient client, LoginMessage loginMessage)
        {
            //Находим пользователя в базе, у которого имя и пароль имеют переданные логин и пароль
            var targetaccount = storage.Find(U => U.Name == loginMessage.Name && U.Password == loginMessage.Password);

            //Если пользователя не найдено
            if (targetaccount == null)
            {
                //отправляем ответ, с инфой о том, что пара логин пароль неверна
                client.Send(new Response(StatusCode.IncorrectLoginOrPassword));
                //Ну и больше ничего не делаем
                return;
            }
            //нашли пользователя, который подходит по переданным параметрам
            client.UserView = targetaccount;
            //Отправляем сообщение что всё хорошо, пользотель вошел
            client.Send(Response.GoodResponse);
        }
Пример #9
0
 public void WhenIAskTheClientInformation()
 {
     try {
         GetClientInformationResponse = RemoteClient.Send <GetClientInformationRequest, GetClientInformationResponse>(new GetClientInformationRequest());
     }
     catch (RemoteClientException ex) {
         Exception = ex;
     }
 }
Пример #10
0
 public void SendPacket(CGPlayerCmd.Builder cg)
 {
     Log.Net("BroadcastMsg: " + cg);
     if (rc != null)
     {
         Bundle bundle;
         var    data = KBEngine.Bundle.GetPacket(cg, out bundle);
         rc.Send(data, bundle);
     }
 }
Пример #11
0
        public static void Start()
        {
            TcpClient tcp = new TcpClient();

            try
            {
                tcp.Connect(IPAddress.Loopback, 11223);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                tcp.Close();
                return;
            }

            RemoteClass myclass = new RemoteClass();

            myclass.AddMethod("wazzap", (client, args) =>
            {
                List <object> list = NetStruct.UnpackFmt(args, 0, "sf");
                if (list == null)
                {
                    return(false);
                }

                Console.WriteLine($"wazzap(): '{(string)list[0]}', '{(float)list[1]}'");
                return(true);
            });

            RemoteClient client = new RemoteClient(tcp, myclass);

            client.RemoteCall("Say_IntString", "isf", 010011, "gANGSTA!", (float)4.20002);
            client.Send();
            client.Recv();
            client.RemoteCall("CloseServer", "");
            client.Send();
            client.Recv();
            tcp.Close();
        }
Пример #12
0
        public static void Start()
        {
            TcpListener tcp = new TcpListener(IPAddress.Loopback, 11223);

            tcp.Start();
            doListen = true;

            RemoteClass myclass = new RemoteClass();

            myclass.AddMethod("Say_IntString", (client, args) =>
            {
                List <object> list = NetStruct.UnpackFmt(args, 0, "isf");
                if (list == null)
                {
                    return(false);
                }

                int i    = (int)list[0];
                string s = (string)list[1];
                float f  = (float)list[2];
                Console.WriteLine($"Say_IntString(): {i}, '{s}', {f}");
                return(true);
            });
            myclass.AddMethod("CloseServer", (client, args) =>
            {
                Console.WriteLine("CloseServer(): Got request to close the server");
                doListen = false;
                return(true);
            });

            do
            {
                TcpClient    client = tcp.AcceptTcpClient();
                RemoteClient remote = new RemoteClient(client, myclass);
                double       flLast = 0.5;
                while (remote.Recv() == RpcCode.Ok)
                {
                    remote.RemoteCall("wazzap", "sf", $"String {flLast}", flLast);
                    flLast += 0.5;
                    remote.Send();
                }
                doListen = false;
                client.Close();
            } while (doListen);

            Console.WriteLine("Stopping server...");
            tcp.Stop();
            doListen = false;
        }
Пример #13
0
        //отправляем список имен пользоваьелей онлайн
        private void SendUsersOnline(RemoteClient client)
        {
            //Получаем список имен, для этого берем клиентов
            var usernames = clients
                            //Берем из них только тех, у которых
                            //имеется отображение аккаунта, то есть они авторизованы
                            .Where(C => C.UserView != null)
                            //Получаем имена этих авторизованных тользователей
                            .Select(C => C.UserView.Name)
                            //Приводим эту последовательность к списку элементов
                            .ToList();

            //Отправляем клиенту этот список, обернув его в OnlineUsersResponse
            client.Send(new OnlineUsersResponse(usernames));
        }
Пример #14
0
    public void SendU3DClientLoginInfoRequest()
    {
        U3DClientLogin u3dClientLogin = new U3DClientLogin()
        {
            m_clientId   = 0,
            m_clientName = "TianShanShan",
        };
        Packet packet = new Packet(u3dClientLogin.m_clientId, 0,
                                   0, 0, u3dClientLogin.Size, u3dClientLogin.Packet2Bytes());

        if (m_remoteClient != null)
        {
            m_remoteClient.Send(packet.Packet2Bytes());
        }
    }
Пример #15
0
        //=============================================================================
        //Methods that affect the client


        public void SendInfoMsg(string msg)
        {
            RemoteClient.Send("INFO:" + msg);
        }
Пример #16
0
        public override void OnRecived(RemoteClient from, Client to)
        {
            Environment.ParentClient.Log(LogLevel.Info, "{1}: загрузить файл {0}", RelativePath,from);
            Environment.ParentClient.Log(LogLevel.Info, "Отправка файла {0} на узел {1}", RelativePath, from);
            base.OnRecived(from, to);

            var newfilename = Path.Combine(ExchageFolder.FullName,specdir, srcFile.Name);
            if (File.Exists(newfilename))
                File.Delete(newfilename);

                if (File.Exists(srcFile.RealPath))
                    File.Copy(srcFile.RealPath, newfilename);
               // else
               //         from.Send(new SendFileMessage());
            from.Send(new SendFileMessage(srcFile,specdir));
        }
Пример #17
0
 public void SendSysMsg(string msg)
 {
     RemoteClient.Send("SYS:" + msg);
 }
Пример #18
0
 public void SendUpdateMsg(string msg)
 {
     RemoteClient.Send("UPD:" + msg);
 }
Пример #19
0
 public void WhenISendAnEchoRequestWithValueThroughTheRemoteClientOnMainThread(int value)
 {
     MainThreadResponses.Add(RemoteClient.Send <EchoRequest, EchoResponse>(new EchoRequest(value.ToString())));
 }
Пример #20
0
 public override void OnRecived(RemoteClient from, Client to)
 {
     if (!Environment.HasRemoteClient(FromId))
     {
         var client = new RemoteClient(FromId, Environment);
         Environment.AddRemoteClient(client);
         client.Send(new mHI());
     }
 }