public void HandleClient(TcpClient client)
 {
     while (!stop)
     {
         try
         {
             NetworkStream stream = client.GetStream();
             BinaryReader  reader = new BinaryReader(stream);
             BinaryWriter  writer = new BinaryWriter(stream);
             {
                 try
                 {
                     // mutex.WaitOne();
                     string jsonString = reader.ReadString();
                     // mutex.ReleaseMutex();
                     var obj = Newtonsoft.Json.JsonConvert.DeserializeObject <CommandEventArgs>(jsonString);
                     CommandEventArgs args = (CommandEventArgs)obj;
                     bool             result;
                     string           logMessage = controller.ExecuteCommand(args.CommandID, args.CommandArgs, out result); //make sure controller has try/catch
                     if (!result)
                     {
                         logger.Log(logMessage, MessageTypeEnum.FAIL);
                         return;
                     }
                     jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(new CommandEventArgs()
                     {
                         CommandID = args.CommandID, CommandArgs = new string[] { logMessage }
                     });
                     mutex.WaitOne();
                     if (args.CommandID != CommandEnum.RemoveHandlerCommand)
                     {
                         writer.Write(jsonString);
                         mutex.ReleaseMutex();
                         mutex.WaitOne();
                     }
                     logger.Log("Command " + args.CommandID.ToString() + " received" + System.Environment.NewLine +
                                "Arguments returned:\n" + logMessage, MessageTypeEnum.INFO);
                     mutex.ReleaseMutex();
                 }
                 catch
                 {
                     ClientDisconnect?.Invoke(this, client);
                     break;
                 }
             }
         }
         catch
         {
             ClientDisconnect?.Invoke(this, client);
             break;
         }
     }
 }
Example #2
0
        /// <summary>
        /// Handles the client.
        /// </summary>
        /// <param name="client">The client.</param>
        public void HandleClient(TcpClient client)
        {
            try
            {
                NetworkStream stream = client.GetStream();
                BinaryReader  reader = new BinaryReader(stream);
                BinaryWriter  writer = new BinaryWriter(stream);
                while (!stop)
                {
                    byte[] readBytes = reader.ReadBytes(4);
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(readBytes);
                    }
                    int    dataLength     = BitConverter.ToInt32(readBytes, 0);
                    byte[] imageNameBytes = reader.ReadBytes(dataLength);
                    string imageName      = System.Text.Encoding.Default.GetString(imageNameBytes);

                    //reading image from bytes
                    readBytes = reader.ReadBytes(4);
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(readBytes);
                    }
                    dataLength = BitConverter.ToInt32(readBytes, 0);
                    byte[] imageBytes = reader.ReadBytes(dataLength);
                    //Image image = byteArrayToImage(imageBytes);

                    if (imageBytes != null && imageName != null)
                    {
                        ImageData imageData = new ImageData()
                        {
                            Name = imageName, ImageBytes = imageBytes
                        };
                        string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(imageData);
                        bool   result;
                        string logMessage = controller.ExecuteCommand(CommandEnum.NewImageCommand, new string[] { jsonString }, out result);
                        //  if (!result) logger.Log(logMessage, MessageTypeEnum.FAIL);
                        //  else logger.Log(logMessage, MessageTypeEnum.INFO);
                    }
                    // else logger.Log("Unable to receive image from connection", MessageTypeEnum.FAIL);
                }
            }
            catch
            {
                ClientDisconnect?.Invoke(this, client);
            }
        }
        public override Gen <Operation <ITcpServerSocketModel, ITcpServerSocketModel> > Next(ITcpServerSocketModel obj0)
        {
            Gen <Operation <ITcpServerSocketModel, ITcpServerSocketModel> > returnGen = null;

            if (obj0.BoundAddress != null && obj0.LocalChannels.Count == 0)
            {
                returnGen = ClientConnect.Generator();
            }
            else
            {
                returnGen = Gen.OneOf(ClientWrite.Generator(), ClientDisconnect.Generator(), ClientConnect.Generator());
            }

            OperationSanityCheck++;
            return(returnGen);
        }
Example #4
0
        /// <summary>
        /// Disconnects the player for the given <paramref name="reason"/>.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="reason">The disconnection reason.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="player"/> or <paramref name="reason"/> are <see langword="null"/>.
        /// </exception>
        public static void Disconnect(this IPlayer player, NetworkText reason)
        {
            if (player is null)
            {
                throw new ArgumentNullException(nameof(player));
            }

            if (reason is null)
            {
                throw new ArgumentNullException(nameof(reason));
            }

            var packet = new ClientDisconnect {
                Reason = reason
            };

            player.SendPacket(packet);
        }
Example #5
0
 internal static void InvokeClientDisconnect(ClientDisconnectEventArgs e)
 {
     ClientDisconnect?.Invoke(e);
 }
Example #6
0
 /// <summary>
 /// Вызов события об отключении
 /// </summary>
 /// <param name="id">ID сокета</param>
 /// <param name="ip">IP адрес подклоючения</param>
 /// <param name="port">Удаленный порт</param>
 private void CallDisconnected(ConnectionValue client)
 {
     Task.Factory.StartNew(() => { ClientDisconnect?.Invoke(this, new Arguments.ClientConnectionArgs(client.SocketID, client.RemoteIP, client.RemotePort)); });
 }
Example #7
0
        // Metoda przetwarzająca polecania wprowadzone przez użytkownika.
        // Wykorzystuje metody statyczne sprawdzające czy wpisane polecenie jest poprawne.
        // W przypadku sukcesu wykonuje odpowiednią operację
        private void ProcessTag(string tag)
        {
            ClientCommand command = null;

            if (HelpTagValidator.Validate(tag))
            {
                PrintHelp();
                return;
            }

            if (ConnectionTagValidator.Validate(tag))
            {
                var ipAddress  = ConnectionTagValidator.GetIpAddress(tag);
                var portNumber = ConnectionTagValidator.GetPortNumber(tag);
                TryToConnect(ipAddress, portNumber);
                StartReceivingIfConnected();
                return;
            }

            if (QuitTagValidator.Validate(tag))
            {
                if (_client.Connected)
                {
                    command  = new ClientDisconnect(_id, _sessionId, _byteSender, _packetFormatter);
                    _quiting = true;
                }
                else
                {
                    QuitProgram();
                }
            }

            // Jeżeli klient nie jest podłączony z serwerem metoda ta kończy się, ponieważ operacje poniżej wymagają
            // połączenia z serwerem do ich realizacji
            if (!_client.Connected)
            {
                PrintInvalidInputOrConnectionRequiredMessage();
                return;
            }

            // Operacje wymagające połączenia z serwerem
            int destinationId;

            switch (tag)
            {
            case var input when IdTagValidator.Validate(input):
                command = new ClientGetId(_id, _sessionId, _byteSender, _packetFormatter);

                break;

            case var input when InviteTagValidator.Validate(input):
                destinationId = int.Parse(InviteTagValidator.GetMatchedValue(tag));

                command = new ClientInvite(_id, destinationId, _sessionId,
                                           _byteSender, _packetFormatter);
                break;

            case var input when AcceptTagValidator.Validate(input):
                destinationId = int.Parse(AcceptTagValidator.GetMatchedValue(tag));

                command = new ClientAcceptInvite(_id, destinationId, _sessionId,
                                                 _byteSender, _packetFormatter);
                break;

            case var input when DeclineTagValidator.Validate(input):
                destinationId = int.Parse(DeclineTagValidator.GetMatchedValue(tag));

                command = new ClientDeclineInvite(_id, destinationId, _sessionId,
                                                  _byteSender, _packetFormatter);
                break;

            case var input when MessageTagValidator.Validate(input):
                var messageToSend = MessageTagValidator.GetMatchedValue(tag);

                command = new ClientSendMessage(_id, _sessionId, _byteSender, _packetFormatter, messageToSend);
                break;

            case var input when CloseTagValidator.Validate(input):
                command = new ClientCloseAndOpenNewSessionCommand(_id, _sessionId, _byteSender, _packetFormatter);

                break;

            case var input when DisconnectTagValidator.Validate(input):
                command = new ClientDisconnect(_id, _sessionId, _byteSender, _packetFormatter);

                break;
            }

            if (command != null)
            {
                _commandHandler.Handle(command);
            }
            else
            {
                PrintInvalidInputMessage();
            }
        }
Example #8
0
 private void Disconnect()
 {
     if (btnConnect.InvokeRequired)
     {
         ClientDisconnect _myInvoke = new ClientDisconnect(Disconnect);
         this.Invoke(_myInvoke);
     }
     else
     {
         m_Client.Close();
         this.btnConnect.Text = "Connect";
     }
 }
Example #9
0
        void ProcessClient(object _client)
        {
            if (!(_client is TcpClient))
            {
                return;
            }

            ClientInfo clientInfo = new ClientInfo {
                isRunning = true,
                thread    = Thread.CurrentThread,
                client    = _client as TcpClient
            };

            clientInfo.stream = clientInfo.client.GetStream();

            lock (clientsLocker) {
                clients.Add(clientInfo);
            }

            byte[] data = new byte[ClientConnect.OneObjectSize];

            {
                ClientConnect         clientConnect;
                ClientConnectResponce responce;

                lock (clientInfo.locker) {
                    while (!clientInfo.stream.DataAvailable)
                    {
                        Thread.Sleep(1);
                    }

                    PacketType type = Protocol.BaseRecieve(clientInfo.stream, out data);
                    if (type == PacketType.ClientConnect)
                    {
                        clientConnect = ClientConnect.Deserialize(data);

                        responce            = ClientConnected(clientConnect);
                        clientInfo.playerId = responce.playerId;
                        clientInfo.Send(PacketType.ClientConnectResponce, ClientConnectResponce.Serialize(responce));

                        List <byte> listWorldState = new List <byte>();
                        foreach (var state in responce.initialWorldState)
                        {
                            listWorldState.AddRange(GameObjectState.Serialize(state));
                        }
                        //Console.WriteLine($"Send {listWorldState.Count} bytes to player {responce.playerId}");
                        clientInfo.Send(PacketType.WorldState, listWorldState.ToArray());
                    }
                    else
                    {
                        throw new Exception("Recieve smth wrong in Server.ProcessClient()");
                    }
                }
            }

            data = new byte[BasePlayerAction.OneObjectSize];
            BasePlayerAction action;

            while (clientInfo.isRunning)
            {
                lock (clientInfo.locker) {
                    if (!clientInfo.stream.DataAvailable)
                    {
                        System.Threading.Thread.Sleep(1);
                        continue;
                    }

                    PacketType type = Protocol.BaseRecieve(clientInfo.stream, out data);
                    if (type == PacketType.PlayerAction)
                    {
                        action          = BasePlayerAction.Deserialize(data);
                        action.playerId = clientInfo.playerId;
                        playerActions.Enqueue(action);
                    }
                    else if (type == PacketType.ClientDisconnect)
                    {
                        clientInfo.isRunning = false;

                        //Console.WriteLine("Client going to disconnect");
                        ClientDisconnect disconnectInfo = ClientDisconnect.Deserialize(data);
                        //Console.WriteLine("Deserialize disconnect data");
                        clientInfo.Send(PacketType.ClientDisconnectResponce, ClientDisconnectResponce.Serialize(
                                            new ClientDisconnectResponce()
                        {
                        }
                                            ));
                        //Console.WriteLine("Send ClientDisconnectResponce");
                    }
                }
            }

            lock (clientsLocker) {
                //Console.WriteLine("Close client streams");
                lock (clientInfo.locker) {
                    clientInfo.stream.Close();
                    clientInfo.client.Close();
                }

                //Console.WriteLine("Try to remove from clients");
                clients.Remove(clientInfo);
            }

            //Console.WriteLine("Close client");
        }
Example #10
0
        protected internal void OnClientDisconect(TcpSocketEventArgs arg)
        {
            ClientDisconnect?.Invoke(this, arg);

            clients.Remove(arg.Client);
        }
Example #11
0
 private void OnClientDisconneted()
 {
     ClientDisconnect?.Invoke(new ActiveClientEventArgs(this));
 }
Example #12
0
        public void Disconnect()
        {
            if (IsDisconnected)
            {
                return;
            }

            IsDisconnected = true;
            //Console.WriteLine("Start disconnect");

            isRunning = false;
            while (clientThread.IsAlive)
            {
                Thread.Sleep(100);
            }
            //Console.WriteLine("clientThread stopped");

            lock (streamLocker) {
                Protocol.BaseSend(stream, PacketType.ClientDisconnect, ClientDisconnect.Serialize(
                                      new ClientDisconnect()
                {
                })
                                  );
                //Console.WriteLine("Send ClientDisconnect");

                while (!stream.DataAvailable)
                {
                    Thread.Sleep(100);
                }

                //Console.WriteLine("Receive ClientDisconnectResponce");

                byte[] data = new byte[ClientDisconnectResponce.OneObjectSize];
                ClientDisconnectResponce responce;

                PacketType type;
                byte       maxReadLoops = 100;
                do
                {
                    type = Protocol.BaseRecieve(stream, out data);
                    if (--maxReadLoops == 0)
                    {
                        break;
                    }
                } while (type != PacketType.ClientDisconnectResponce);

                if (type == PacketType.ClientDisconnectResponce)
                {
                    responce = ClientDisconnectResponce.Deserialize(data);
                    //Console.WriteLine("Deserialize ClientDisconnectResponce");
                }
                else
                {
                    throw new Exception("Wait for PacketType.ClientDisconnectResponce, but maxReadLoops(now 100) reached 0");
                }
            }

            stream.Close();
            client.Close();

            //Console.WriteLine("End disconnect");
        }
 private void OnDisconnect(ConnectEventArgs e)
 {
     UnityEngine.Debug.Log("OnDisconnect");
     ClientDisconnect?.Invoke(this, e);
 }
Example #14
0
 private void SRV_ClientDisconect(Client sender)
 {
     Clients.Remove(sender);
     ClientDisconnect?.Invoke(sender.Name);
 }
 private void OnClientDisconnect(PacketReceivedEventArgs packetReceivedEventArgs)
 {
     ClientDisconnect?.Invoke(this, packetReceivedEventArgs);
 }
Example #16
0
        static void ReceiveCallBack(IAsyncResult ar)
        {
            StateObject       state        = (StateObject)ar.AsyncState;
            Socket            clientSocket = state.Socket;
            int               bytesRead    = clientSocket.EndReceive(ar);
            string            text         = Encoding.UTF8.GetString(state.Buffer, 0, bytesRead);
            ClientInformation senderClient = GetClientInformation(clientSocket);

            WriteConsole(string.Format("Received data from client {0}: {1}", senderClient.Name, text));
            if (!string.IsNullOrEmpty(text))
            {
                object element = XMLManager.Deserialize(text);
                if (element is SendMessage sendMessage)
                {
                    BroadcastMessage broadcastMessage     = new BroadcastMessage(senderClient.Name, sendMessage.Text);
                    string           broadcastMessageText = XMLManager.Serialize(broadcastMessage);
                    foreach (ClientInformation client in _clients)
                    {
                        BeginSend(client, broadcastMessageText);
                    }
                }
                else if (element is ChangeNameRequest cnr)
                {
                    if (string.IsNullOrEmpty(cnr.Name))
                    {
                        BeginSend(senderClient, XMLManager.Serialize(new ErrorResponse((int)ErrorCode.InvalidName)));
                    }
                    else if (IsNameUnique(cnr.Name))
                    {
                        string changeNameResponseText = XMLManager.Serialize(new ChangeNameResponse(senderClient.Name, cnr.Name));
                        foreach (ClientInformation client in _clients)
                        {
                            BeginSend(client, changeNameResponseText);
                        }
                        senderClient.Name = cnr.Name;
                    }
                    else
                    {
                        BeginSend(senderClient, XMLManager.Serialize(new ErrorResponse((int)ErrorCode.NameAlreadyExists)));
                    }
                }
                else if (element is ChallengeRequest challengeRequest)
                {
                    ClientInformation challengeeClient = GetClientInformation(challengeRequest.ChallengeeName);
                    if (challengeeClient.State == ClientState.Available)
                    {
                        senderClient.ChangeStateToChallenge(challengeeClient.Id);
                        challengeeClient.ChangeStateToChallenge(senderClient.Id);
                        BeginSend(senderClient, XMLManager.Serialize(new ChallengePendingResponse()
                        {
                            ChallengeeName = challengeRequest.ChallengeeName
                        }));
                        BeginSend(challengeeClient, XMLManager.Serialize(new ChallengeRequest(senderClient.Name)));
                    }
                    else if (challengeeClient.State == ClientState.Challenge)
                    {
                        BeginSend(senderClient, XMLManager.Serialize(new ErrorResponse((int)ErrorCode.ClientAlreadyChallenged)));
                    }
                    else if (challengeeClient.State == ClientState.Duel)
                    {
                        BeginSend(senderClient, XMLManager.Serialize(new ErrorResponse((int)ErrorCode.ClientAlreadyInDuel)));
                    }
                    else
                    {
                        throw new InvalidOperationException("Unknown client state.");
                    }
                }
                else if (element is CancelChallengeRequest)
                {
                    ClientInformation challengeeClient = GetClientInformation(senderClient.OtherClientId);
                    senderClient.ChangeStateToAvailable();
                    challengeeClient.ChangeStateToAvailable();
                    BeginSend(senderClient, XMLManager.Serialize(new CancelChallengeRequest()));
                    BeginSend(challengeeClient, XMLManager.Serialize(new CancelChallengeResponse()
                    {
                        Challenger = senderClient.Name
                    }));
                }
                else if (element is DeclineChallengeRequest)
                {
                    ClientInformation challengerClient = GetClientInformation(senderClient.OtherClientId);
                    senderClient.ChangeStateToAvailable();
                    challengerClient.ChangeStateToAvailable();
                    BeginSend(senderClient, XMLManager.Serialize(new DeclineChallengeRequest()));
                    BeginSend(challengerClient, XMLManager.Serialize(new DeclineChallengeResponse()
                    {
                        Challengee = senderClient.Name
                    }));
                }
                else if (element is AcceptChallengeRequest)
                {
                    //TODO: implement properly
                    ClientInformation challengerClient = GetClientInformation(senderClient.OtherClientId);
                    senderClient.ChangeStateToAvailable();
                    challengerClient.ChangeStateToAvailable();
                    BeginSend(senderClient, XMLManager.Serialize(new AcceptChallengeRequest()));
                    BeginSend(challengerClient, XMLManager.Serialize(new AcceptChallengeResponse()
                    {
                        Challengee = senderClient.Name
                    }));
                }
                else
                {
                    throw new ArgumentOutOfRangeException("element");
                }
                BeginReceive(clientSocket);
            }
            else
            {
                senderClient.Socket.Shutdown(SocketShutdown.Both);
                senderClient.Socket.Close();
                _clients.Remove(senderClient);
                WriteConsole(string.Format("{0} disconnected.", senderClient.Name));
                ClientDisconnect clientDisconnect     = new ClientDisconnect(senderClient.Name);
                string           clientDisconnectText = XMLManager.Serialize(clientDisconnect);
                foreach (ClientInformation client in _clients)
                {
                    BeginSend(client, clientDisconnectText);
                }
            }
        }
Example #17
0
 private void Manager_OnDisconnect(PacketManager sender)
 {
     ClientDisconnect?.Invoke(this);
 }
Example #18
0
 /// <summary>
 /// 引发客户端断开连接事件
 /// </summary>
 /// <param name="ipAddr">IP地址</param>
 /// <param name="port">端口号</param>
 protected virtual void OnClientDisconnect(IPAddress ipAddr, int port)
 {
     ClientDisconnect?.Invoke(this,
                              new TCPClientDisConnectedEventArgs(ipAddr, port));
 }