Ejemplo n.º 1
0
 void DisconnectUser()
 {
     if (isConnected)
     {
         client.Disconnect(ID);
         client = null;
         tbUserName.IsEnabled = true;
         bConnDicon.Content   = "Connect";
         isConnected          = false;
     }
 }
 public string[] Execute(string[] arguments)
 {
     if (client.connected)
     {
         client.Disconnect();
         return(new string[] { "Disconnected!" });
     }
     else
     {
         return(new string[] { "Not connected to a server." });
     }
 }
Ejemplo n.º 3
0
    private void Process(object s, SocketAsyncEventArgs e)
    {
        try
        {
            if (e.SocketError == SocketError.Success)
            {
                ServerClient T = new ServerClient(e.AcceptSocket, _BufferSize, _MaxPacketSize);

                lock (_Clients)
                {
                    if (_Clients.Count < _MaxConnections)
                    {
                        _Clients.Add(T);
                        T.StateChanged         += HandleStateChanged;
                        T.ExceptionThrown      += OnClientExceptionThrown;
                        T.ReadPacket           += OnClientReadPacket;
                        T.ReadProgressChanged  += OnClientReadProgressChanged;
                        T.WritePacket          += OnClientWritePacket;
                        T.WriteProgressChanged += OnClientWriteProgressChanged;

                        OnClientStateChanged(T, true);
                    }
                    else
                    {
                        T.Disconnect();
                    }
                }

                e.AcceptSocket         = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                e.AcceptSocket.NoDelay = true;

                if (_KeepAlive)
                {
                    e.AcceptSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 20000);
                }

                if (!Handle.AcceptAsync(e))
                {
                    Process(null, e);
                }
            }
            else
            {
                OnExceptionThrown(new SocketException((int)e.SocketError));
                Disconnect();
            }
        }
        catch (Exception ex)
        {
            OnExceptionThrown(ex);
            Disconnect();
        }
    }
Ejemplo n.º 4
0
        private static void Main(string[] args)
        {
            var serverClient = new ServerClient();
            serverClient.Connect();
            var chatClient = serverClient.GetChatClient();
            var message = chatClient.Echo("I am so damn good!");
            serverClient.Disconnect();

            Console.WriteLine("Connection was successful!");
            Console.WriteLine("Server returned: {0}", message);
            Console.ReadLine();
        }
Ejemplo n.º 5
0
        public override void Execute(ServerClient client, string[] args)
        {
            if (args.Length != 2)
            {
                SendUsage(client);
                return;
            }

            string username = args[0];
            string password = args[1];

            UserAccount account = UserAccount.Attempt(username, password);

            if (account == null)
            {
                client.SendMessage("§2Invalid username/password.");
                return;
            }

            ServerClient foundClient = ClientRepository.Instance.Find(account.Username);

            if (foundClient != null)
            {
                if (!foundClient.Equals(client))
                {
                    foundClient.Disconnect("§2This username has been reclaimed by the account owner.");
                }
            }

            string oldUsername = client.Username;

            client.Account  = account;
            client.Username = account.Username;
            client.SendMessage("§4You are now authenticated as " + account.Username + "!");

            if (client.Channel == null)
            {
                client.JoinChannel(ChannelRepository.Instance.GetLobby());
            }

            if (!oldUsername.Equals("%"))
            {
                client.Channel.BroadcastMessage("§1" + oldUsername + " is now known as " + account.Username);
            }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            InstanceContext instanceContext = new InstanceContext(new MessageCallback());
            var             client          = new ServerClient(instanceContext);

            Console.WriteLine("Введите имя для подключения:");
            string name        = Console.ReadLine();
            int    connectId   = client.Connect(name);
            var    allAbonents = client.ShowAbonents(connectId);

            while (true)
            {
                string a = Console.ReadLine();
                if (a == "s")
                {
                    allAbonents = client.ShowAbonents(connectId);
                    foreach (var index in allAbonents)
                    {
                        Console.WriteLine(index.Value.id + " " + index.Value.name + " " + index.Value.status);
                    }
                }
                if (a == "d")
                {
                    client.Disconnect(connectId);
                }
                if (a == "c")
                {
                    client.Connect(name);
                }
                if (a == "send")
                {
                    client.SendMessage(connectId, null, "Привет всем");
                }
                if (a == "p")
                {
                    var d = client.ProvideMessage(connectId);
                    allAbonents = client.ShowAbonents(connectId);
                    foreach (var index in d)
                    {
                        Console.WriteLine(allAbonents[index.SenderId].name + " : " + index.TextOfMessage);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        private void DisconnectMethod()
        {
            client.Disconnect(id);
            client             = null;
            OutputMessage.Text = string.Empty;


            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            // AllABonents.Items[id] = InputName.Text + " — Offline";
            this.ControlBox            = false;
            InputName.ReadOnly         = false;
            this.ControlBox            = false;
            this.Text                  = "Login";
            this.AllABonents.Enabled   = false;
            this.InputMessage.Enabled  = false;
            this.SendButton.Enabled    = false;
            this.OutputMessage.Enabled = false;
            ConnectButton.Text         = "Connect";
            isConnected                = false;
        }
Ejemplo n.º 8
0
        private void DisconnectMethod()
        {
            client.Disconnect(id);
            client = null;
            status = Status.Offline;

            //Метод работы со списком
            DrawAbonentList(userName, status, allAbonents);

            OutputMessage.Enabled = false;
            OutputMessage.Clear();
            SendButton.Enabled     = false;
            InputMessage.Enabled   = false;
            AbonentList.Enabled    = false;
            ConnDisconnButton.Text = "Connect";
            InputName.ReadOnly     = false;
            ShowButton.Enabled     = false;
            ForAllCheck.Enabled    = false;
            this.Text = "Login";
        }
Ejemplo n.º 9
0
        private void ListenForClients()
        {
            TcpListener listener = new TcpListener(IPAddress.Any, Port);

            listener.Start();
            while (!PanicMode)
            {
                TcpClient    tcpClient    = listener.AcceptTcpClient();
                ServerClient serverClient = new ServerClient(tcpClient);

                if (_channelRepository.GetLobby() == null)
                {
                    serverClient.Disconnect("§2Server Error: No Lobby!");
                    continue;
                }

                Thread clientThread = new Thread(new ThreadStart(new ServerConnection(serverClient).HandleMessages));
                clientThread.Start();
            }
        }
Ejemplo n.º 10
0
        //-----------------------------------------------------SocketListener------------------------
        //客户端链接进来时
        private void OnSocketListenerConnectedEx(ServerClient sender)
        {
            int i = 0;

            if (BlackList.TryGetValue(((IPEndPoint)sender.RemoteEndPoint).Address, out i))
            {
                //sender.SendMessage(new ServiceDesc{Type = (byte)MessageType.DROP, ClientId = 30});
                sender.Disconnect();
                return;
            }

            sender.MessageReceived += OnSocketListenerMessageReceivedEx;
            var clientId = GetUniqueClientId((uint)mId, sender.ClientId);
            //Logger.Fatal("Gate Connect ------ 1---{0} -- {1}", DateTime.Now.ToBinary(), clientId);
            var characterInfo = new CharacterInfoEx();

            characterInfo.mState   = GateClientState.NotAuthorized;
            characterInfo.ClientId = clientId;

            Logger.Info("Client: " + clientId + " connected.");

            sender.UserData = characterInfo;
            mFromClientId2Client.AddOrUpdate(characterInfo.ClientId, sender, (l, arg2) => sender);
        }
Ejemplo n.º 11
0
        //客户端有消息发过来时
        private void OnSocketListenerMessageReceivedEx(ServerClient client, ServiceDesc desc)
        {
            GateServerMonitor.ReceivePacketNumber.Mark();
            if (null != desc && null != desc.Data)
            {
                GateServerMonitor.ReceivePacketSize.Mark(desc.Data.Length);
            }

            if (desc.Type == (int)MessageType.Ping)
            {
                client.SendMessage(desc);
                return;
            }

            Logger.Debug("Received a message from Client {0}.", client.ClientId);
            var characterInfo = client.UserData as CharacterInfoEx;

            if (characterInfo == null)
            {
                Logger.Error("Internal error for ClientMessageReceived: " + desc.ServiceType);
                return;
            }

            if (characterInfo.Last1000MessageCount == 0)
            {
                characterInfo.Last1000Message = DateTime.Now;
            }

            characterInfo.Last1000MessageCount++;

            if (characterInfo.Last1000MessageCount == 1000)
            {
                characterInfo.Last1000MessageCount = 0;
                var duration = (DateTime.Now - characterInfo.Last1000Message).TotalMilliseconds;
                if (duration < 1000)
                {
                    Logger.Error("Add {0} to black list.", ((IPEndPoint)client.RemoteEndPoint).Address);
                    BlackList.TryAdd(((IPEndPoint)client.RemoteEndPoint).Address, 0);
                    //client.SendMessage(new ServiceDesc { Type = (byte)MessageType.DROP, ClientId = 30 });
                    client.Disconnect();
                }
            }

            if (!mCSFunctionId2Name.ContainsKey((int)desc.FuncId))
            {
                characterInfo.Last1000MessageCount = 0;
                Logger.Error("Add {0} to black list because attack by funcid {1}.", ((IPEndPoint)client.RemoteEndPoint).Address, desc.FuncId);
                BlackList.TryAdd(((IPEndPoint)client.RemoteEndPoint).Address, 0);
                client.Disconnect();
                //client.SendMessage(new ServiceDesc { Type = (byte)MessageType.DROP, ClientId = 30 });
                return;
            }

            switch (characterInfo.mState)
            {
            case GateClientState.NotAuthorized:
            {
                //只要验证账号密码函数通过
                if (desc.FuncId != 2001 &&  //PlayerLoginByUserNamePassword
                    desc.FuncId != 2002 &&     //PlayerLoginByThirdKey
                    desc.FuncId != 2031 &&     //QueryServerTimezone
                    desc.FuncId != 2014 &&     //SyncTime
                    desc.FuncId != 2034 &&     //ReConnet
                    desc.FuncId != 2037        // SendDeviceUdid
                    )
                {
                    Logger.Info("OnSocketListenerMessageReceivedEx NotAuthorized FuncId: {0}", desc.FuncId);
                    return;
                }

                List <SocketClient> serverClient;
                if (mFromId2Servers.TryGetValue(ServiceType.Login, out serverClient))
                {
                    try
                    {
                        //characterInfo.Servers[(int)ServiceType.Login] = serverClient[0];
                        desc.ClientId = characterInfo.ClientId;
                        try
                        {
                            desc.Routing.Add((ulong)IpToInt(((IPEndPoint)(client.RemoteEndPoint)).Address.ToString()));
                        }
                        catch { }
                        serverClient[0].SendMessage(desc);
                    }
                    catch (Exception ex)
                    {
                        Logger.WarnException("OnSocketListenerMessageReceivedEx NotAuthorized WarnException", ex);
                    }
                }
                else
                {
                    Logger.Info("OnSocketListenerMessageReceivedEx NotAuthorized LoginNotConnet");
                }
            }
            break;

            case GateClientState.Login:
            {
                if (desc.ServiceType != (int)ServiceType.Login)
                {
                    Logger.Error("OnSocketListenerMessageReceivedEx Login FuncId: {0}", desc.FuncId);
                    return;
                }
                SocketClient serverClient;
                if (characterInfo.Servers.TryGetValue((int)ServiceType.Login, out serverClient))
                {
                    try
                    {
                        desc.ClientId = characterInfo.ClientId;
                        serverClient.SendMessage(desc);
                    }
                    catch (Exception ex)
                    {
                        Logger.WarnException("OnSocketListenerMessageReceivedEx Login WarnException", ex);
                    }
                }
                else
                {
                    Logger.Info("OnSocketListenerMessageReceivedEx Login LoginNotConnet");
                }
            }
            break;

            case GateClientState.GamePlay:
            {
                SocketClient serverClient;
                if (characterInfo.Servers.TryGetValue(desc.ServiceType, out serverClient))
                {
                    try
                    {
                        desc.ClientId    = characterInfo.ClientId;
                        desc.CharacterId = characterInfo.CharacterId;
                        serverClient.SendMessage(desc);
                    }
                    catch (Exception ex)
                    {
                        Logger.WarnException("OnSocketListenerMessageReceivedEx GamePlay WarnException", ex);
                    }
                }
                else
                {
                    Logger.Info("OnSocketListenerMessageReceivedEx GamePlay LoginNotConnet");
                }
            }
            break;
            }
        }