Ejemplo n.º 1
0
        public void MultipleClientsTransmittingToSameServerTest()
        {
            SimpleTcpServer server = new SimpleTcpServer().Start(8911);

            server.Delimiter = Encoding.UTF8.GetBytes("0")[0];
            SimpleTcpClient client1 = new SimpleTcpClient().Connect(server.GetListeningIPs().FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString(), 8911);
            SimpleTcpClient client2 = new SimpleTcpClient().Connect(server.GetListeningIPs().FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString(), 8911);

            System.Threading.Thread.Sleep(1000);
            if (server.ConnectedClientsCount < 2)
            {
                Assert.Fail("Server did not register 2 connected clients");
            }

            string dataRecievedByServer = "";

            server.DelimiterDataReceived += (sender, msg) =>
            {
                dataRecievedByServer += msg.MessageString;
            };

            client1.Write("1111");
            System.Threading.Thread.Sleep(100);
            client2.Write("2222");
            System.Threading.Thread.Sleep(100);
            client1.Write("0");

            System.Threading.Thread.Sleep(1000);

            Assert.AreEqual("1111", dataRecievedByServer);

            server.Stop();
        }
Ejemplo n.º 2
0
 private void InputBox_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter)
     {
         // MessageBox.Show("Enter");
         client.Write(JmenoBox.Text + ": " + InputBox.Text);
         InputBox.Text = "";
     }
 }
Ejemplo n.º 3
0
        private void OnButton_Click(object sender, RoutedEventArgs e)
        {
            var buffer = new byte[3];

            buffer[0] = 0x1F; buffer[2] = 0x01;
            buffer[1] = XorChecksum(buffer, buffer.Length);
            _client.Write(buffer);
            AddLogInfo(buffer, true);
        }
Ejemplo n.º 4
0
 public void client_broadcast(string message)
 {
     message = "output::{&var}{&quot}" + message + "{&quot}";
     byte[] data = Scorpion_RSA.Scorpion_RSA.encrypt_data(message, rsa_public_key);
     tcp_cl.Write(data);
     return;
 }
Ejemplo n.º 5
0
        public void StartClient(string ip, int port, string nodeName)
        {
            _client = new SimpleTcpClient();
            _client.Connect(ip, port);
            _client.Write($"INIT {nodeName}");

            _logService.LogInfo("Connected do Management");

            _client.DataReceived += OnRowInfoReceived;
        }
Ejemplo n.º 6
0
 public void SendMessage(string content)
 {
     _tcpClient.Write(JsonConvert.SerializeObject(new MessageTransmission(_restService.AuthorizationHeader,
                                                                          new Message
     {
         Content   = content,
         CreatedAt = DateTime.Now,
         SenderId  = _restService.LoggedInUser.Id
     })));
 }
Ejemplo n.º 7
0
        private void ConnectToServer(int port)
        {
            const string ipAddress = "127.0.0.1";

            Logger.Info($"Connecting to {ipAddress}:{port}");

            _client = new SimpleTcpClient().Connect(ipAddress, port);
            _client.DataReceived += Client_DataReceived;
            _client.Write("ClientReadyToWork");
            Logger.Info("Connected");

            PlayStateNotifier.OnPlaymodeExit += PlayStateNotifier_OnPlaymodeExit;
        }
Ejemplo n.º 8
0
        public void Send(PacketType type, Action <object> cb = null, object data = null)
        {
            var packet = new Packet()
            {
                Type = type,
                Data = data
            };

            lock (Callbacks)
            {
                packet.ID = Callbacks.Count;
                while (Callbacks.ContainsKey(packet.ID))
                {
                    packet.ID++;
                }
                Callbacks.Add(packet.ID, cb);
            }

            try
            {
                client.Write(Helper.ObjectToByteArray(packet));
            }
            catch (Exception) { MessageBox.Show("Kan ikke sende til serveren"); }
        }
Ejemplo n.º 9
0
        private void log_Click(object sender, EventArgs e)
        {
            string login    = text_user.Text;
            string password = SHA.ChangeToSHA2_256(text_password.Text);

            if (login.Length == 0 || text_password.Text.Length == 0)
            {
                MessageBox.Show("Pole login i hasło nie mogą być puste!");
            }
            else
            {
                client.Write(diffieHellman.EncryptMessage("LOG;" + login + ";" + password));
                login_name = login;
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            var client = new SimpleTcpClient().Connect("10.10.10.5", 3490);

            Console.WriteLine("Enter command ...");
            ConsoleKeyInfo key_input = Console.ReadKey();

            while (key_input.Key != ConsoleKey.Escape)
            {
                switch (key_input.Key)
                {
                case ConsoleKey.W:
                {
                    client.Write(rasp_cmds[(int)eRaspCommands.RASP_TKCTRL_START]);
                    break;
                }

                case ConsoleKey.S:
                {
                    client.Write(rasp_cmds[(int)eRaspCommands.RASP_TKCTRL_STOP]);
                    break;
                }

                case ConsoleKey.A:
                {
                    client.Write(rasp_cmds[(int)eRaspCommands.RASP_TKCTRL_LEFT]);
                    break;
                }

                case ConsoleKey.D:
                {
                    client.Write(rasp_cmds[(int)eRaspCommands.RASP_TKCTRL_RIGHT]);
                    break;
                }

                case ConsoleKey.Backspace:
                {
                    client.Write(rasp_cmds[(int)eRaspCommands.RASP_SRV_SHUTDOWN]);
                    break;
                }

                default:
                    break;
                }

                key_input = Console.ReadKey();
            }

            client.Write(rasp_cmds[(int)eRaspCommands.RASP_SRV_DISCONNECT]);
            client.Disconnect();
        }
Ejemplo n.º 11
0
        public static Message WriteAndGetReply(this SimpleTcpClient client,
                                               string data,
                                               TimeSpan timeout)
        {
            Message mReply = null;

            void onReceived(object s,
                            Message e) => mReply = e;

            client.DataReceived += onReceived;
            client.Write(data);
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            while (mReply == null && stopwatch.Elapsed < timeout)
            {
                Thread.Sleep(10);
            }
            client.DataReceived -= onReceived;
            return(mReply);
        }
Ejemplo n.º 12
0
        public void RequestCreateAccount(Account account)
        {
            CreateAccountProtocol ptc = new CreateAccountProtocol();

            ptc.Account = account;
            BasicPacket packet = new BasicPacket();

            packet.Opcode = 1;
            packet.Data   = ptc.ToBytes();
            _client.Write(packet.ToBytes());
        }
Ejemplo n.º 13
0
        //Force update
        public bool Update(CrossServerMessage Message)
        {
            if (_Market.IsHostServer)
            {
                string MarketServerData = JsonConvert.SerializeObject(Message);
                //Write to file and broadcast to all clients!
                Hangar.Debug("Sending new market data to clients! " + Message.Type.ToString());
                if (Message.Type == MessageType.AddItem)
                {
                    //Main.Debug("Point1");
                    Server.BroadcastLine(MarketServerData);
                    //Main.Debug("Point2");
                    //Update server.
                    GridMarket.GridList.Add(Message.List[0]);
                    //Main.GridDefinition.Add(Message.GridDefinition[0]);


                    //Send update to clients on this game server!
                    Comms.AddSingleItem(Message.List[0]);
                    //Main.Debug("Point3");

                    //Save data to file (This is server!)
                    MarketData Data = new MarketData();
                    Data.List = GridMarket.GridList;
                    FileSaver.Save(Path.Combine(Hangar.Dir, "Market.json"), Data);
                }
                else if (Message.Type == MessageType.RemoveItem)
                {
                    Server.BroadcastLine(MarketServerData);

                    //Update server.
                    GridMarket.GridList.Remove(Message.List[0]);
                    //Main.GridDefinition.RemoveAll(Message.GridDefinition[0]);
                    //Main.GridDefinition.RemoveAll(x => x.name == Message.List[0].Name);

                    //Send update to clients on this game server!
                    Comms.RemoveSingleItem(Message.List[0]);


                    //Save data to file (This is server!)
                    MarketData Data = new MarketData();
                    Data.List = GridMarket.GridList;
                    FileSaver.Save(Path.Combine(Hangar.Dir, "Market.json"), Data);
                }
                else if (Message.Type == MessageType.PlayerAccountUpdated)
                {
                    //Do nothing. (Send data to server and wait for reply)

                    Server.BroadcastLine(MarketServerData);


                    foreach (PlayerAccount account in Message.BalanceUpdate)
                    {
                        Utils.TryUpdatePlayerBalance(account);

                        if (!GridMarket.PlayerAccounts.ContainsKey(account.SteamID))
                        {
                            if (!account.AccountAdjustment)
                            {
                                GridMarket.PlayerAccounts.Add(account.SteamID, account.AccountBalance);
                            }
                        }
                        else
                        {
                            if (!account.AccountAdjustment)
                            {
                                GridMarket.PlayerAccounts[account.SteamID] = account.AccountBalance;
                            }
                            else
                            {
                                //Add this to the general list
                                GridMarket.PlayerAccounts[account.SteamID] = account.AccountBalance + GridMarket.PlayerAccounts[account.SteamID];
                            }
                        }
                    }

                    Accounts accounts = new Accounts();
                    accounts.PlayerAccounts = GridMarket.PlayerAccounts;

                    FileSaver.Save(Path.Combine(Hangar.Dir, "PlayerAccounts.json"), accounts);
                }
                else if (Message.Type == MessageType.PlayerOnline)
                {
                    //Server found the player online! (By Joining)
                    //var first = Message.BalanceUpdate.First();
                    //ulong key = first.Key;


                    // Main.PlayerAccountUpdate.Remove(key);

                    //Broadcast to all clients!
                    Server.BroadcastLine(MarketServerData);
                }
                else if (Message.Type == MessageType.PurchasedGrid)
                {
                    var t = Task.Run(() => _Market.PurchaseGrid(Message.GridDefinition[0]));
                }
                //File.WriteAllText(Path.Combine(Main.Dir, "Market.json"), JsonConvert.SerializeObject(Data));
            }
            else
            {
                try
                {
                    string MarketClientData = JsonConvert.SerializeObject(Message);
                    //Send to server to get reply
                    Client.Write(MarketClientData);

                    if (Message.Type == MessageType.AddItem)
                    {
                        //Send update to clients on this game server!
                        Comms.AddSingleItem(Message.List[0]);
                    }
                    else if (Message.Type == MessageType.RemoveItem)
                    {
                        //Send update to clients on this game server!
                        Comms.RemoveSingleItem(Message.List[0]);
                    }
                }
                catch (System.IO.IOException e)
                {
                    //Server no longer responding? Perhaps it shutdown? Or restarted?
                    //This means THIS server needs to be the new server

                    //Or this is an old client needing to be re-connected to server. This means we need to redo/Reconnect everything!
                    Hangar.Debug("Server closed! Trying to Update!", e, Hangar.ErrorType.Warn);
                    //Remove client DataRecieved Event!
                    Client.DelimiterDataReceived -= Client_DelimiterDataReceived;

                    //Re run create servers and client class!
                    CreateServers();

                    //Re run the update
                    Update(Message);
                }
                catch (Exception g)
                {
                    Hangar.Debug("CrossServer Market Network Failed Fatally!", g, Hangar.ErrorType.Fatal);
                }
            }


            return(true);
        }
Ejemplo n.º 14
0
        private void ProcessReceivedCommands()
        {
            if (!_commandsAndDatas.Any())
            {
                return;
            }
            if (_currentData != null)
            {
                return;
            }

            _currentData = _commandsAndDatas.Dequeue();

            Logger.Info($"Start to process command. CommandType = {_currentData.CommandType}");

            switch (_currentData.CommandType)
            {
            case CommandType.CreateFuzzyPartition:
            {
                if (_currentData.PartitionSettings.IsCenterPlacingTask)
                {
                    var result = _partitionRunner.CreateFuzzyPartitionWithCentersPlacing(_currentData.PartitionSettings, _currentData.RenderingSettings);
                    _client.Write(result.ToBytes());
                }
                else
                {
                    var result = _partitionRunner.CreateFuzzyPartitionWithFixedCenters(_currentData.PartitionSettings, _currentData.RenderingSettings);
                    _client.Write(result.ToBytes());
                }

                _currentData = null;
            }
            break;

            case CommandType.ShowPartitionAtIterationIndex:
            {
                //if (_currentData.IterationNumber >= _partitionImageByIterations.Count)
                //{
                //    Logger.Error($"Error: iteration number {_currentData.IterationNumber} bigger then existing {_partitionImageByIterations.Count} partition images count.");
                //    return;
                //}

                //_partitionRunner.show

                _partitionRunner.DrawPartitionAtIteration(_currentData.RenderingSettings.IterationNumber);
            }
            break;

            case CommandType.SavePartitionImage:
            {
                if (_currentData.ImageSavePath == null)
                {
                    _partitionRunner.SavePartitionImage(null);
                }
                else
                {
                    var path = Encoding.UTF8.GetString(_currentData.ImageSavePath);
                    _partitionRunner.SavePartitionImage(path);
                }

                _currentData = null;
            }
            break;

            case CommandType.ShowCurrentPartitionWithSettings:
            {
                _partitionRunner.RedrawPartitionWithSettings(_currentData.RenderingSettings);
                _currentData = null;
            }
            break;
            }
        }