Exemple #1
0
    //Read messages
    protected void PopMessages()
    {
        if (!isStarted)
        {
            return;
        }

        int recHostID;
        int connectionID;
        int channelID;

        byte[] recBuffer = new byte[BUFF_SIZE];
        int    dataSize;

        NetworkEventType type = NetworkTransport.Receive(
            out recHostID,    //client platform id
            out connectionID, //client id
            out channelID,    //channel id
            recBuffer,
            BUFF_SIZE,
            out dataSize,
            out error
            );

        switch (type)
        {
        case NetworkEventType.ConnectEvent:
            SClient newclient = new SClient(connectionID);
            clients.Add(connectionID, newclient);
            OnClientConnected(newclient);

            if (SHOW_LOGS)
            {
                string logMsg = String.Format("Connected user {0}", connectionID);
                Debug.Log(logMsg);
            }
            break;

        case NetworkEventType.DisconnectEvent:
            SClient oldclient = clients[connectionID];
            clients.Remove(connectionID);
            OnClientDisconnected(oldclient);

            if (SHOW_LOGS)
            {
                string logMsg = String.Format("Disconnected user {0}", connectionID);
                Debug.Log(logMsg);
            }
            break;

        case NetworkEventType.DataEvent:
            ReadMessage(recBuffer, connectionID);
            break;

        default:
        case NetworkEventType.Nothing:
        case NetworkEventType.BroadcastEvent:
            break;
        }
    }
        void SetClient(int index, SClient Client)
        {
            ListViewItem item;

            if (LvClients.Items.Count <= index)
            {
                item = new ListViewItem
                {
                    Text = Client.SocketHandle.ToString()
                };

                item.SubItems.Add(Client.IPAddress);
                item.SubItems.Add(Client.UserName);
                item.SubItems.Add(Client.OperatingSystem);
                item.Tag = (object)Client;

                LvClients.BeginUpdate();
                LvClients.Items.Add(item);
                LvClients.EndUpdate();

                return;
            }

            item                  = LvClients.Items[index];
            item.Text             = Client.SocketHandle.ToString();
            item.SubItems[0].Text = Client.IPAddress;
            item.SubItems[1].Text = Client.UserName;
            item.SubItems[2].Text = Client.OperatingSystem;
            item.Tag              = (object)Client;

            LvClients.BeginUpdate();
            LvClients.Items[index] = item;
            LvClients.EndUpdate();
        }
Exemple #3
0
 public void Clientconnected()
 {
     while (true)
     {
         TcpClient client = server.AcceptTcpClient();
         Console.WriteLine("Connection accepted.");
         string nickname = "";
         try
         {
             while (nickname.Length == 0)
             {
                 Byte[] bytes = new Byte[client.Available];
                 if (client.GetStream().Read(bytes, 0, bytes.Length) > 0)
                 {
                     nickname = Encoding.Unicode.GetString(bytes, 0, bytes.Length);
                 }
             }
             Console.WriteLine("Client " + nickname + " connected.");
             SClient newClient = new SClient();
             newClient.tcp      = client;
             newClient.nickname = nickname;
             clientList.Add(newClient);
             var threading = new Thread(() => checkIncomingMessage(newClient));
             threading.Start();
             sendMessagetoClients(nickname + " joined the club.", null);
         }
         catch
         {
             Console.WriteLine("Failed to get nickname");
             break;
         }
     }
 }
        public string Resolve(string message)
        {
            if (message.Contains("GetUser"))
            {
                Log("[Server]: Resolving GetUser request");
                string[] parameters = message.Split(':');
                SClient  user       = ClientService.GetUser(Int32.Parse(parameters[1])).Result;

                MemoryStream stream = new MemoryStream();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SClient));
                serializer.WriteObject(stream, user);

                stream.Position = 0;
                StreamReader sr     = new StreamReader(stream);
                string       output = sr.ReadToEnd();

                return(output);
            }
            else if (message.Contains("GetProduct"))
            {
                Log("[Server]: Resolving GetProduct request");
                string[] parameters = message.Split(':');
                SProduct product    = ProductService.GetProduct(Int32.Parse(parameters[1]));

                MemoryStream stream = new MemoryStream();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SProduct));
                serializer.WriteObject(stream, product);

                byte[] json = stream.ToArray();
                stream.Close();
                string result = Encoding.UTF8.GetString(json, 0, json.Length);
                return(Encoding.UTF8.GetString(json, 0, json.Length));
            }
            else if (message.Contains("GetAllProducts"))
            {
                Log("[Server]: Resolving GetAllProducts request");
                IEnumerable <SProduct> products = ProductService.GetProducts();

                List <SProduct> serializationList = new List <SProduct>();

                foreach (SProduct prod in products)
                {
                    serializationList.Add(prod);
                }

                MemoryStream stream = new MemoryStream();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List <SProduct>));
                serializer.WriteObject(stream, serializationList);

                byte[] json = stream.ToArray();
                stream.Close();
                string result = Encoding.UTF8.GetString(json, 0, json.Length);

                return(Encoding.UTF8.GetString(json, 0, json.Length));
            }
            else
            {
                return("Can't process given message");
            }
        }
        public void UpdateTest()
        {
            DataContext dataContext = new DataContext {
                SClients = new List <SClient>()
            };
            SClientRepository ClientRepository = new SClientRepository(dataContext);
            SClient           client           = new SClient
            {
                Id       = -1,
                Age      = 18,
                Cart     = new SCart(),
                Name     = "John",
                LastName = "Doe"
            };

            ClientRepository.Add(client);

            string  newName = "Jack";
            SClient client2 = new SClient
            {
                Id       = -1,
                Age      = 32,
                Cart     = new SCart(),
                Name     = newName,
                LastName = "Doe"
            };

            ClientRepository.Update(-1, client2);
            Assert.AreEqual(newName, ClientRepository.Get(-1).Name);
        }
        public void FilterTest()
        {
            DataContext dataContext = new DataContext {
                SClients = new List <SClient>()
            };
            SClientRepository ClientRepository = new SClientRepository(dataContext);
            SClient           client           = new SClient
            {
                Id       = -1,
                Age      = 18,
                Cart     = new SCart(),
                Name     = "John",
                LastName = "Doe"
            };
            SClient client2 = new SClient
            {
                Id       = -2,
                Age      = 32,
                Cart     = new SCart(),
                Name     = "Jack",
                LastName = "Sparrow"
            };

            ClientRepository.Add(client);
            ClientRepository.Add(client2);

            List <SClient> clients = ClientRepository.Get(c => c.Age == 32).ToList();

            Assert.AreEqual(1, clients.Count());
        }
Exemple #7
0
 public void Disconnect(string reason, params object[] values)
 {
     Console.WriteLine("Disconnected client with reason: " + string.Format(reason, values));
     if (SClient != null)
     {
         SClient.Disconnect();
     }
 }
Exemple #8
0
        public SClient Update(int id, SClient entity)
        {
            SClient client = _dataContext.SClients.FirstOrDefault(c => c.Id == id);

            client.LastName = entity.LastName;
            client.Name     = entity.Name;
            client.Age      = entity.Age;
            client.Cart     = entity.Cart;

            return(client);
        }
Exemple #9
0
        public static SClient MapClient(Client client)
        {
            SClient sclient = new SClient
            {
                Id       = client.Id,
                Name     = client.Name,
                LastName = client.LastName,
                Age      = DateTime.Now.Year - client.DateOfBirth.Year,
                Cart     = MapCart(client.Cart)
            };

            return(sclient);
        }
Exemple #10
0
        public static ClientDTO MapClient(SClient client)
        {
            ClientDTO clientDTO = new ClientDTO
            {
                Id       = client.Id,
                Name     = client.Name,
                LastName = client.LastName,
                Age      = client.Age,
                Cart     = MapCart(client.Cart)
            };

            return(clientDTO);
        }
        static SClient GetClientStructFromConnection(SConnection Connection)
        {
            SClientIntroduction ClientIntroduction = (SClientIntroduction)Connection.Information;

            SClient ClientInfo = new SClient
            {
                IPAddress       = Connection.ClientSocket.GetIPv4(),
                SocketHandle    = Connection.ClientSocket.GetHandle(),
                UserName        = ClientIntroduction.UserName,
                OperatingSystem = ClientIntroduction.OperatingSystem
            };

            return(ClientInfo);
        }
 private void Connection_OnUpdateClient(int index, SClient Client)
 {
     if (InvokeRequired)
     {
         this.Invoke((MethodInvoker) delegate()
         {
             SetClient(index, Client);
         });
     }
     else
     {
         SetClient(index, Client);
     }
 }
Exemple #13
0
        public void SendPacket(PacketWriter packet)
        {
            if (ServerConstants.PrintPackets)
            {
                ServerConsole.Info(String.Format("Sending: {0}", Functions.ByteArrayToStr(packet.ToArray())));
            }

            if (SClient == null)
            {
                return;
            }

            SClient.SendPacket(packet);
            //LastPacketsSent.Enqueue(packet);
        }
Exemple #14
0
        public void StartSession <T>(SClient Client)
        {
            IControllerSession session = (IControllerSession)Activator.CreateInstance <T>();

            session.Client     = Client;
            session.Connection = Connection;

            lock (Sessions)
            {
                session.Id = GenerateSessionId();

                Sessions.Add(session);
            }

            SendIntroduction(session);
        }
Exemple #15
0
        public Form1()
        {
            Init();

            runHashCode = DateTime.UtcNow.ToString().GetHashCode();
            InitializeComponent();
            watch = System.Diagnostics.Stopwatch.StartNew();
            this.MainMenuStrip.Hide();
            this.textBox1.Hide();
            this.trackBar1.Hide();
            client = new SClient();
            Task.Factory.StartNew(() =>
            {
                client.Init();
            });
        }
        private void ParseMessege(string message)
        {
            MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(message));

            try
            {
                SProduct deserializedObject           = new SProduct();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(deserializedObject.GetType());
                deserializedObject = serializer.ReadObject(memoryStream) as SProduct;

                DbContext.Instance.SProducts.Add(deserializedObject);
            }
            catch (SerializationException e)
            {
                try
                {
                    List <SProduct>            deserializedObject = new List <SProduct>();
                    DataContractJsonSerializer serializer         = new DataContractJsonSerializer(typeof(List <SProduct>));

                    memoryStream.Position = 0;
                    deserializedObject    = serializer.ReadObject(memoryStream) as List <SProduct>;

                    foreach (SProduct prod in deserializedObject)
                    {
                        DbContext.Instance.SProducts.Add(prod);
                    }
                }
                catch (SerializationException ee)
                {
                    try
                    {
                        SClient deserializedObject            = new SClient();
                        DataContractJsonSerializer serializer = new DataContractJsonSerializer(deserializedObject.GetType());
                        deserializedObject = serializer.ReadObject(memoryStream) as SClient;

                        DbContext.Instance.SClients.Add(deserializedObject);
                    }
                    catch (SerializationException eeee)
                    {
                        return;
                    }
                }
            }

            memoryStream.Close();
        }
Exemple #17
0
        internal void Disconnected()
        {
            MapleCharacter save = null;

            if (Account != null)
            {
                save = Account.Character;
            }

            try
            {
                if (Account != null)
                {
                    Account.Release(); //It is imperative to release the account before removing the client from the server.
                }
            }
            catch { }
            try
            {
                if (Connected)
                {
                    ServerConsole.Info(String.Format("{0}:{1} Disconnected", Host, Port));
                }
                Connected = false;
                Program.RemoveClient(this);
                if (save != null)
                {
                    save.LoggedOut();
                }
            }
            catch { }
            try
            {
                if (NpcEngine != null)
                {
                    NpcEngine.Dispose();
                }
            }
            catch { }
            try
            {
                SClient.Dispose();
            }
            catch { }
        }
        public void AddTest()
        {
            DataContext dataContext = new DataContext {
                SClients = new List <SClient>()
            };
            SClientRepository ClientRepository = new SClientRepository(dataContext);
            SClient           client           = new SClient
            {
                Id       = -1,
                Age      = 18,
                Cart     = new SCart(),
                Name     = "John",
                LastName = "Doe"
            };

            ClientRepository.Add(client);
            Assert.IsNotNull(ClientRepository.Get(-1));
        }
Exemple #19
0
        void OnClientsSync(EDataSyncType type, int index, object data)
        {
            if (type == EDataSyncType.Remove)
            {
                if (OnRemoveClient != null)
                {
                    OnRemoveClient.Invoke(index);
                }
            }
            else
            {
                if (OnUpdateClient != null)
                {
                    SClient client = CSerialization.Deserialize <SClient>((byte[])data);

                    OnUpdateClient.Invoke(index, client);
                }
            }
        }
        static public void Execute(List <SConnection> Connections)
        {
            List <SClient> clients = new List <SClient>();

            for (int ClientIndex = 0; ClientIndex < Connections.Count; ClientIndex++)
            {
                if (Connections[ClientIndex].ConnectionType != EConnectionType.Client)
                {
                    continue;
                }

                if (Connections[ClientIndex].Information == null)
                {
                    continue;
                }

                SClient ClientInfo = GetClientStructFromConnection(Connections[ClientIndex]);

                clients.Add(ClientInfo);
            }

            for (int ConnectionIndex = 0; ConnectionIndex < Connections.Count; ConnectionIndex++)
            {
                if (Connections[ConnectionIndex].ConnectionType != EConnectionType.Controller)
                {
                    continue;
                }

                SConnection            ControllerConnection  = Connections[ConnectionIndex];
                SControllerInformation ControllerInformation = (SControllerInformation)ControllerConnection.Information;

                if (!ControllerInformation.IsAuthorized)
                {
                    continue;
                }

                SynchronizeStructArray <SClient>(ESyncList.Clients, clients, ref ControllerInformation.Clients, ControllerConnection.ClientSocket);

                ControllerConnection.Information = ControllerInformation;
                Connections[ConnectionIndex]     = ControllerConnection;
            }
        }
        public void DeleteTest()
        {
            DataContext dataContext = new DataContext {
                SClients = new List <SClient>()
            };
            SClientRepository ClientRepository = new SClientRepository(dataContext);
            SClient           client           = new SClient
            {
                Id       = -1,
                Age      = 18,
                Cart     = new SCart(),
                Name     = "John",
                LastName = "Doe"
            };

            ClientRepository.Add(client);
            ClientRepository.Delete(-1);

            Assert.AreEqual(0, ClientRepository.Get().ToList().Count());
        }
Exemple #22
0
        public void SendHandshake()
        {
            if (SClient == null)
            {
                return;
            }

            uint sIV = Functions.RandomUInt();
            uint rIV = Functions.RandomUInt();

            SClient.Crypto.SetVectors(sIV, rIV);

            PacketWriter writer = new PacketWriter();

            writer.WriteShort(0x0E);
            writer.WriteUShort(ServerConstants.Version);
            writer.WriteMapleString(ServerConstants.SubVersion.ToString());
            writer.WriteUInt(rIV);
            writer.WriteUInt(sIV);
            writer.WriteByte(8); //ServerIdent
            SClient.SendRawPacket(writer.ToArray());
        }
Exemple #23
0
 public SClient Add(SClient entity)
 {
     _dataContext.SClients.Add(entity);
     return(entity);
 }
Exemple #24
0
        public void Delete(int id)
        {
            SClient client = _dataContext.SClients.FirstOrDefault(c => c.Id == id);

            _dataContext.SClients.Remove(client);
        }
Exemple #25
0
 protected abstract void OnClientDisconnected(SClient client);
Exemple #26
0
        public void checkIncomingMessage(SClient client)
        {
            TcpClient newClient = client.tcp;

            try
            {
                while (!client.isClosed())
                {
                    NetworkStream stream = newClient.GetStream();
                    if (stream != null)
                    {
                        while (!stream.DataAvailable)
                        {
                            ;
                        }
                        Byte[] bytes = new Byte[newClient.Available];
                        stream.Read(bytes, 0, bytes.Length);
                        string line = Encoding.Unicode.GetString(bytes, 0, bytes.Length);
                        if (line.Length > 0)
                        {
                            if (line[0] == '#')
                            {
                                //Removes the # from the line.
                                //line = line.Substring(1);
                                //Console.WriteLine(line);
                                string rest;
                                if (wordInString(line, "#%READY%#", out rest))
                                {
                                    sendMessagetoClients(client.nickname + " is ready for hängagubbe.", null);
                                    Console.WriteLine(client.nickname + " is ready for hängagubbe.");
                                    client.gameReady = true;
                                }
                                else if (wordInString(line, "#%GUESS%#", out rest) && lastGuess.Length == 0)
                                {
                                    if (rest.Length > 0)
                                    {
                                        Console.WriteLine("Guess:" + rest);
                                        rest      = rest.ToLower();
                                        lastGuess = rest;
                                    }
                                }
                            }
                            else
                            {
                                line  = client.nickname;
                                line += ": ";
                                line += Encoding.Unicode.GetString(bytes, 0, bytes.Length);
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(line);
                                sendMessagetoClients(line, null);
                                Console.ForegroundColor = ConsoleColor.Blue;
                            }
                        }
                    }
                }
            }
            catch
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Failed to read message from client");
                Console.ForegroundColor = ConsoleColor.Blue;
            }
        }
Exemple #27
0
        public GameClientTest()
        {
            InitializeComponent();

            try
            {
                var SetupJson = (JsonDataObject)JsonParser.Parse(File.ReadAllText("Option.ini"));

                _Auto    = SetupJson["Auto"].GetBool();
                ServerNo = SetupJson["ServerNo"].GetInt32();
                var ServerInfo = ((JsonDataObject)(((JsonDataArray)SetupJson["Servers"])[ServerNo]));

                StartNum  = ServerInfo["StartNum"].GetUInt32();
                ClientCnt = ServerInfo["ClientCnt"].GetInt32();
                if (ClientCnt <= 0)
                {
                    throw new Exception("Invalid ClientCnt");
                }

                DataPath = ServerInfo["DataPath"].GetString();
                IP       = ServerInfo["IP"].GetString();
                Port     = ServerInfo["Port"].GetUInt16();

                ID = ServerInfo["ID"].GetString();
                PW = ServerInfo["PW"].GetString();

                TimerNet.Enabled = true;

                if (_Auto)
                {
                    btnLoginUID.Enabled = false;
                }

                btnDisconnect.Enabled = false;

                _Net = new rso.game.CClient(
                    Link, LinkFail, UnLink, Recv, LinkSoft, UnLinkSoft,
                    Check, CheckFail,
                    new SVersion(0, 0));
                if (_Net == null)
                {
                    return;
                }

                _Binder = new CClientBinder(_Net);

                _Clients = new SClient[ClientCnt];

                for (TPeerCnt i = 0; i < ClientCnt; ++i)
                {
                    _Clients[i] = new SClient(i);
                    _Clients[i].Initialize();
                }

                _Binder.AddSendProto <SGameProtoNetCs>((Int32)EProtoNetCs.GameProto);

                _Binder.AddRecvProto((Int32)EProtoNetSc.GameProto, GameProtoNetSc);

                TimerNet.Enabled = true;
                _Graphics        = this.CreateGraphics();
            }
            catch (Exception Exception_)
            {
                _Log(Exception_.ToString());
                return;
            }
        }
Exemple #28
0
 protected override void OnClientDisconnected(SClient client)
 {
     // Debug.Log("Client disconnected");
 }