public void AddClient(ClientObject obj)
 {
     lock (this.clientObjects)
     {
         for (int i = 0; i < this.clientObjects.Length; i++)
         {
             if (this.clientObjects[i] == null)
             {
                 this.clientObjects[i] = obj;
                 break;
             }
         }
     }
 }
Esempio n. 2
0
        // прослушивание входящих подключений
        protected internal void Listen()
        {
            try
            {
                _tcpListener = new TcpListener(IPAddress.Parse(TcpConfig.Ip), TcpConfig.Port);
                _tcpListener.Start();
                Console.WriteLine("Server started. Waiting for connections...");

                while (true)
                {
                    TcpClient tcpClient = _tcpListener.AcceptTcpClient();

                    ClientObject clientObject = new ClientObject(tcpClient, this);
                    Thread       clientThread = new Thread(clientObject.Process);
                    clientThread.Start();
                    Console.WriteLine("Client connected");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Disconnect();
            }
        }
Esempio n. 3
0
 static void Main(string[] args)
 {
     try {
         listener = new TcpListener(IPAddress.Parse(address), port);
         listener.Start();
         Console.WriteLine("Ожидание подключений...");
         while (true)
         {
             var client       = listener.AcceptTcpClient();
             var clientObject = new ClientObject(client);
             var clientThread = new Thread(clientObject.Process);
             clientThread.Start();
         }
     }
     catch (Exception ex) {
         Console.WriteLine(ex.Message);
     }
     finally {
         if (listener != null)
         {
             listener.Stop();
         }
     }
 }
Esempio n. 4
0
        public static void AddClientToQueue(ClientObject client)
        {
            switch (client.NumberofQuestions)
            {
            case "5":
                string matchType = "5";
                clientQueue5.Enqueue(client);
                if (clientQueue5.Count >= 2)
                {
                    ClientObject client1 = clientQueue5.Dequeue();
                    ClientObject client2 = clientQueue5.Dequeue();
                    CreateMatch(client1, client2, matchType);
                }
                else
                {
                    try
                    {
                        clientQueue5.Dequeue();
                        AddClientToQueue(client);
                    }
                    catch
                    {
                        break;
                    }
                }

                break;

            case "10":
                matchType = "10";
                clientQueue10.Enqueue(client);
                Thread.Sleep(10000);
                if (clientQueue10.Count >= 2)
                {
                    ClientObject client1 = clientQueue10.Dequeue();
                    ClientObject client2 = clientQueue10.Dequeue();
                    CreateMatch(client1, client2, matchType);
                }
                else
                {
                    try
                    {
                        clientQueue10.Dequeue();
                        AddClientToQueue(client);
                    }
                    catch
                    {
                        break;
                    }
                }
                break;

            case "15":
                matchType = "15";
                clientQueue15.Enqueue(client);
                if (clientQueue15.Count >= 2)
                {
                    ClientObject client1 = clientQueue15.Dequeue();
                    ClientObject client2 = clientQueue15.Dequeue();
                    CreateMatch(client1, client2, matchType);
                }
                else
                {
                    try
                    {
                        clientQueue15.Dequeue();
                        AddClientToQueue(client);
                    }
                    catch
                    {
                        break;
                    }
                }
                break;

            case "20":
                matchType = "20";
                clientQueue20.Enqueue(client);
                if (clientQueue20.Count >= 2)
                {
                    ClientObject client1 = clientQueue20.Dequeue();
                    ClientObject client2 = clientQueue20.Dequeue();
                    CreateMatch(client1, client2, matchType);
                }
                else
                {
                    try
                    {
                        clientQueue20.Dequeue();
                        AddClientToQueue(client);
                    }
                    catch
                    {
                        break;
                    }
                }
                break;
            }
        }
Esempio n. 5
0
 public ReceiveScreenImage(ClientObject client, System.Windows.Controls.Image screenImage)
 {
     this.client = client;
     image       = screenImage;
 }
Esempio n. 6
0
        private static List <Message> HandleDestroyConnectionMessage(Message message, ClientObject client)
        {
            var result = new List <Message>();

            var destroyMessage = (DestroyMessage)message;

            destroyMessage.IsBroadcast  = false;
            destroyMessage.IsSuccessful = false;

            result.Add(destroyMessage);

            var cardToDestroy = Table.OpenedCards.FirstOrDefault(c =>
                                                                 c.Coordinates.Coordinate_X == destroyMessage.Coordinates.Coordinate_X &&
                                                                 c.Coordinates.Coordinate_Y == destroyMessage.Coordinates.Coordinate_Y);

            if (cardToDestroy == null || cardToDestroy is StairsCard || cardToDestroy is GoldCard || cardToDestroy.Gold > 0 || cardToDestroy.IsTroll)
            {
                return(result);
            }

            if (cardToDestroy != null)
            {
                destroyMessage.IsBroadcast  = true;
                destroyMessage.IsSuccessful = true;
                Table.OpenedCards.Remove(cardToDestroy);

                var updateMessage = ProvidePlayerNewCards(client.Id, new List <int> {
                    destroyMessage.CardId
                });
                result.Add(updateMessage);

                var directMessage = SetNextPlayer();
                result.Add(directMessage);
                result.Add(PrepareGoldMessage());
                if (CheckGameEnd())
                {
                    result.Add(CreateEndGameMessage());
                }
            }

            Table.UpdateAllConnections();
            return(result);
        }
Esempio n. 7
0
        public static List <Message> HandleMessage(Message message, ClientObject client)
        {
            var type = message.MessageType;

            Logger.Write($"Received {type.ToString()} message from client {client.Id}");

            switch (type)
            {
                #region Lobby messages
            case GameMessageType.ClientConnectedMessage:
                return(HandleClientConnectedMessage(message, client.Id));

            case GameMessageType.RetrieveAllGamesMessage:
                return(HandleRetrieveAllGamesMessage(message));

            case GameMessageType.CreateGameMessage:
                return(HandleCreateGameMessage(message, client.Id));

            case GameMessageType.JoinMessage:
                return(HandleJoinGameMessage(message as JoinGameMessage, client.Id));

                #endregion

            case GameMessageType.StartGameMessage:
                return(HandleStartGameMessage(message));



            case GameMessageType.InitializeMessage:
                return(HandleInitializeMessage(message, client));

            case GameMessageType.TextMessage:
                return(HandleTextMessage(message, client));

            case GameMessageType.ReadyToPlay:
                return(HandleReadyToPlayMessage(message, client));

            case GameMessageType.BuildMessage:
                return(HandleBuildMessage(message, client));

            case GameMessageType.ActionMessage:
                return(HandleActionMessage(message, client));

            case GameMessageType.DestroyConnectionMessage:
                return(HandleDestroyConnectionMessage(message, client));

            case GameMessageType.ExploreMessage:
                return(HandleExploreMessage(message, client));

            case GameMessageType.FoldMessage:
                return(HandleFoldMessage(message, client));

            case GameMessageType.FoldForFixMessage:
                return(HandleFoldForFixMessage(message, client));

            case GameMessageType.RotateGoldCardMessage:
                return(HandleRotateGoldCardMessage(message));

            case GameMessageType.KeyMessage:
                return(HandleKeyMessage(message, client));

            default: throw new NotImplementedException();
            }
        }
Esempio n. 8
0
        private static void AsyncReceiveCallback(IAsyncResult ar)
        {
            ClientObject co = ar.AsyncState as ClientObject;

            if (co.client.Connected)
            {
                try
                {
                    co.client.EndReceive(ar);

                    if (Encoding.UTF8.GetString(co.buffer).Contains("recv"))
                    {
                        string receiveLoginData = Encoding.UTF8.GetString(co.buffer);
                        if (standardSignalObj.ServerScreenData != null)
                        {
                            standardSignalObj.ServerScreenData = imageData;
                        }
                    }
                    else if (Encoding.UTF8.GetString(co.buffer).Contains("info"))
                    {
                        string receiveLoginData = Encoding.UTF8.GetString(co.buffer);

                        // 해시테이블에 학생 정보 저장 또는 연결 해제
                        if (!LoginRecord(co.address, receiveLoginData.Split('&')[1]))
                        {
                            co.client.Close();
                        }
                    }
                    else if (co.buffer.Length > 4)
                    {
                        ImageOutput(co.address, co.buffer);
                    }

                    Byte[] signal = SignalObjToByte(standardSignalObj);
                    co.client.BeginSend(signal, 0, signal.Length, SocketFlags.None, AsyncSendCallback, co.client);

                    signal = null;
                    Array.Clear(co.buffer, 0, co.buffer.Length);

                    if (standardSignalObj.IsMonitoring)
                    {
                        co.buffer = new Byte[327675];
                    }
                    else
                    {
                        co.buffer = new Byte[4];
                    }

                    co.client.BeginReceive(co.buffer, 0, co.buffer.Length, SocketFlags.None, AsyncReceiveCallback, co);
                }
                catch (SocketException)
                {
                    if (!isFinish)
                    {
                        Control[] ctrl = clientsViewer.clientsViewPanel.Controls.Find("pan_" + co.address, false);
                        if (ctrl.Length > 0)
                        {
                            if (clientsViewer.IsHandleCreated)
                            {
                                clientsViewer.Invoke(clientsViewer.DPD, ctrl[0] as Panel);
                            }
                            else
                            {
                                clientsViewer.clientsViewPanel.Controls.Remove(ctrl[0] as Panel);
                            }
                        }

                        if (clientsViewer.clientsList.ContainsKey(co.address))
                        {
                            clientsViewer.clientsList.Remove(co.address);
                        }

                        //co.client.Close();
                        //co = null;
                    }
                }
                catch (ObjectDisposedException)
                {
                    return;
                }
            }
        }
Esempio n. 9
0
 public void AddConnection(ClientObject clientObject)
 {
     clients.Add(clientObject);
 }
Esempio n. 10
0
 public void Remove(ClientObject cl) => Clients.Remove(cl);
Esempio n. 11
0
 public void Add(ClientObject cl) => Clients.Add(cl);
Esempio n. 12
0
 public void Remove(ClientObject cl, int grupid)
 {
     grups.Find(x => x.GroupId == grupid).Remove(cl);
     cl.GroupId = -1;
 }
Esempio n. 13
0
 public void Add(ClientObject cl, int grupid)
 {
     grups.Find(x => x.GroupId == grupid).Add(cl);
     cl.GroupId = grupid;
 }
Esempio n. 14
0
 public static void ClientCall(ClientObject client, string message)
 {
     NetworkComms.SendObject("Message", client.IP, 43987, message);
 }
Esempio n. 15
0
        protected internal bool UserConnectionIsRepeated(string userName, ClientObject curClient)
        {
            ClientObject client = clients.FirstOrDefault(c => c.UserName == userName);

            return(client != null && client != curClient);
        }
Esempio n. 16
0
        /// <summary> Метод для завершения соединения </summary>
        /// <param name="clientObject"> <summary> Переменная соединения </summary> </param>
        /// <param name="t"> <summary> Переменная потока, в котором поддерживается соединение </summary> </param>
        /// <param name="Choice"> <summary> Выбор конфигурации удаления: 1 - Два соединения; 2 - Удаление вручную; 3 - Удаление в ходе работы программы; </summary> </param>
        public void KillConnect(ClientObject clientObject, BackgroundWorker t, int Choice)
        {
            if (clientObject.InProccesKill == false)
            {
                clientObject.InProccesKill = true;
            }
            else
            {
                return;
            }
            try
            {
                int counter = 0;
                switch (Choice)
                {
                case 1:     // 2 соединения
                    foreach (var item in User_LB.Items)
                    {
                        if (item.ToString() == clientObject.MYIpClient)
                        {
                            counter++;
                            if (counter > 1)
                            {
                                User_LB.Items.Remove(item);
                                break;
                            }
                        }
                    }
                    break;

                case 2:     // Сам

                    User_LB.Items.Remove(User_LB.SelectedItem);

                    break;

                case 3:
                    foreach (var item in User_LB.Items)
                    {
                        if (item.ToString() == clientObject.MYIpClient)
                        {
                            User_LB.Items.Remove(item);
                            break;
                        }
                    }
                    break;

                default:
                    break;
                }

                clientObject.DisconectMes();
                Thread.Sleep(50);
                BWL.Remove(t);
                CO.Remove(clientObject);
            }
            catch (Exception ex)
            {
                StatusBox.Text += "\r\n(" + DateTime.Now.ToString() + ") Ошибка: " + ex.ToString() + "\r\n Место ошибки: Метод KillConnect";
            }
        }
Esempio n. 17
0
 protected internal ClientObject GetAccountFoOrherOperation(string accounNumber, ClientObject curClient)
 {
     foreach (var client in clients)
     {
         var account = client.Accounts?.FirstOrDefault(c => c.Number == accounNumber);
         if (account != null && client != curClient)
         {
             return(client);
         }
     }
     return(null);
 }
Esempio n. 18
0
        private static List <Message> HandleBuildMessage(Message message, ClientObject client)
        {
            Logger.Write($"Build message was received from client {client.Id}");

            var result = new List <Message>();

            var buildMessage = (BuildMessage)message;

            result.Add(buildMessage);

            // check if user can build card
            if (Validator.ValidateBuildingTunnelAction(buildMessage.RouteCard, Table.OpenedCards, buildMessage.RoleType))
            {
                buildMessage.IsSuccessfulBuild = true;
                buildMessage.IsBroadcast       = true;

                var updateMessage = ProvidePlayerNewCards(client.Id, new List <int> {
                    buildMessage.CardId
                });
                result.Add(updateMessage);

                Table.AddCard(buildMessage.RouteCard, buildMessage.RoleType);

                var goldCardsToOpen = Table.GoldCards
                                      .Where(goldCard =>
                                             goldCard.Coordinates.IsNeighbour(buildMessage.RouteCard.Coordinates) &&
                                             (!goldCard.IsOpen || !Table.OpenedCards.Contains(goldCard)))
                                      .ToList();

                var rotateMessage = new RotateGoldCardMessage();
                foreach (var goldCard in goldCardsToOpen)
                {
                    if (Validator.CheckForGold(goldCard, Table.OpenedCards, buildMessage.RoleType) &&
                        Validator.CheckForGold((GoldCard)goldCard.Rotate(), Table.OpenedCards, buildMessage.RoleType))
                    {
                        rotateMessage.CardsToRotate.Add(goldCard);
                    }
                    else
                    {
                        if (!Validator.CheckForGold(goldCard, Table.OpenedCards, buildMessage.RoleType))
                        {
                            goldCard.Rotate();
                        }
                    }

                    goldCard.IsOpen = true;
                    Table.OpenedCards.Add(goldCard);
                    var exploreMessage = new ExploreMessage();
                    exploreMessage.IsBroadcast = true;
                    exploreMessage.Card        = goldCard;
                    exploreMessage.Coordinates = goldCard.Coordinates;

                    result.Add(exploreMessage);
                }

                if (rotateMessage.CardsToRotate.Count > 0)
                {
                    result.Add(rotateMessage);
                }
                else
                {
                    var directMessage = SetNextPlayer();
                    result.Add(directMessage);
                }

                if (CheckGameEnd())
                {
                    result.Add(CreateEndGameMessage());
                }

                Table.UpdateAllConnections(buildMessage.RoleType);
                result.Add(PrepareGoldMessage());
                result.Add(new UpdateTokensMessage(Table.Tokens));

                Logger.Write($"Build message was sent from client {client.Id}");
            }
            else
            {
                buildMessage.IsSuccessfulBuild = false;
                buildMessage.IsBroadcast       = false;

                Logger.Write($"Can't build message was sent for client {client.Id}");
            }


            return(result);
        }
Esempio n. 19
0
 protected internal void BroadcastMessage(string message, ClientObject client)
 {
     byte[] data = Encoding.Unicode.GetBytes(message);
     client.Stream.Write(data, 0, data.Length);
 }
Esempio n. 20
0
        private static List <Message> HandleActionMessage(Message message, ClientObject client)
        {
            var result        = new List <Message>();
            var actionMessage = (ActionMessage)message;

            var resultMessage = new ActionMessage
            {
                IsSuccessful = false,
                RecepientId  = actionMessage.RecepientId,
                SenderId     = actionMessage.SenderId,
            };

            var player = Table.Players.FirstOrDefault(pl => pl.Id == actionMessage.RecepientId);

            switch (actionMessage.ActionType)
            {
            case ActionType.BreakLamp:
                if (!player.BrokenEquipments.Contains(Equipment.Lamp))
                {
                    resultMessage.IsSuccessful = true;
                    player.BrokenEquipments.Add(Equipment.Lamp);
                }

                break;

            case ActionType.BreakPick:
                if (!player.BrokenEquipments.Contains(Equipment.Pick))
                {
                    resultMessage.IsSuccessful = true;
                    player.BrokenEquipments.Add(Equipment.Pick);
                }

                break;

            case ActionType.BreakTrolley:
                if (!player.BrokenEquipments.Contains(Equipment.Trolley))
                {
                    resultMessage.IsSuccessful = true;
                    player.BrokenEquipments.Add(Equipment.Trolley);
                }

                break;

            case ActionType.FixLamp:
                if (player.BrokenEquipments.Contains(Equipment.Lamp))
                {
                    resultMessage.IsSuccessful = true;
                    player.BrokenEquipments.Remove(Equipment.Lamp);
                }

                break;

            case ActionType.FixPick:
                if (player.BrokenEquipments.Contains(Equipment.Pick))
                {
                    resultMessage.IsSuccessful = true;
                    player.BrokenEquipments.Remove(Equipment.Pick);
                }

                break;

            case ActionType.FixTrolly:
                if (player.BrokenEquipments.Contains(Equipment.Trolley))
                {
                    resultMessage.IsSuccessful = true;
                    player.BrokenEquipments.Remove(Equipment.Trolley);
                }

                break;
            }

            resultMessage.Players     = Table.Players;
            resultMessage.IsBroadcast = true;
            result.Add(resultMessage);

            if (resultMessage.IsSuccessful)
            {
                var updateMessage = ProvidePlayerNewCards(client.Id, new List <int> {
                    actionMessage.CardId
                });
                result.Add(updateMessage);

                var directMessage = SetNextPlayer();
                result.Add(directMessage);
                result.Add(PrepareGoldMessage());
                if (CheckGameEnd())
                {
                    result.Add(CreateEndGameMessage());
                }
            }

            return(result);
        }
Esempio n. 21
0
 protected internal void BroadcastOperationResult(string result, ClientObject fromClient, ClientObject toClient = null)
 {
     byte[] data = Encoding.Unicode.GetBytes(result);
     fromClient.Stream.Write(data, 0, data.Length);
     toClient?.Stream.Write(data, 0, data.Length);
 }
Esempio n. 22
0
        List <ClientObject> clients = new List <ClientObject>(); // все подключения

        protected internal void AddConnection(ClientObject clientObject)
        {
            clients.Add(clientObject);
        }
Esempio n. 23
0
 void RefreshTest(ClientObject clientObject)
 {
     clientObject.test = test;
 }