Example #1
0
        private void InternalReceve(IAsyncResult AR)
        {
            SocketError SE    = SocketError.SocketError;
            int         bytes = NetworkSocket?.EndReceive(AR, out SE) ?? 0;

            if (SE != SocketError.Success)
            {
                Disconnect(new SocketException());
                return;
            }

            byte[] packet = Defragger.Process(bytes);

            ReceveWithDefragger();

            if (packet != null)
            {
                try {
                    IPacket pack = Packager.Unpack(packet, PackagingConfiguration);
                    ReceveCallback(this, pack);
                } catch (Exception ex) {
                    Disconnect(ex);
                    return;
                }
            }
        }
Example #2
0
        private void HandleSendQueue()
        {
            QueuedPacket packet = null;

            lock (SyncLock)
            {
                packet = SendQueue.Dequeue();
            }

            if (packet != null && packet.Data != null)
            {
                var se = SocketError.SocketError;

                NetworkSocket?.Send(packet.Data, 0, packet.Data.Length, SocketFlags.None, out se);

                if (se != SocketError.Success)
                {
                    Disconnect(new SocketException());
                    return;
                }
                else
                {
                    packet.HasBeenSent(this);
                }
            }
        }
Example #3
0
        private void InternalReceve(IAsyncResult at)
        {
            var se    = SocketError.SocketError;
            var bytes = NetworkSocket?.EndReceive(at, out se) ?? 0;

            if (se != SocketError.Success)
            {
                Disconnect(new SocketException());
                return;
            }

            var packet = Defragger.Process(bytes);

            ReceiveWithDefragger();

            if (packet != null)
            {
                try
                {
                    var pack = Packager.Unpack(packet, PackagingConfiguration);
                    ReceveCallback(this, pack);
                }
                catch (Exception ex)
                {
                    Disconnect(ex);
                    return;
                }
            }
        }
        public virtual void Shutdown(string reason)
        {
            LogWrite("Performing shutdown (" + reason + ")");
//#if DEBUG
            // just send all delayed packets; since we won't have the possibility to do it after socket is closed
            SendDelayedPackets(NetTime.Now + this.SimulatedMinimumLatency + this.SimulatedLatencyVariance + 1000.0);
//#endif

            try
            {
                if (m_socket != null)
                {
                    // This throws an exception under mono for linux, so we just ingnore it.
                    try
                    {
                        //m_socket.Shutdown(SocketShutdown.Receive);
                    }
                    catch (SocketException) {}
                    m_socket.Close(2);
                }
            }
            finally
            {
                m_socket  = null;
                m_isBound = false;
            }
            m_shutdownComplete = true;

            LogWrite("Socket closed");
        }
Example #5
0
 public void Dispose()
 {
     if (NetworkSocket != null && NetworkSocket.Connected)
     {
         NetworkSocket.Shutdown(SocketShutdown.Both);
     }
 }
Example #6
0
                public void Send(params object[] args)
                {
                    try
                    {
                        byte[] serilisedData = Formatter.Serialize(args);
                        if (Encryption != null)
                        {
                            serilisedData = Encryption.Encrypt(serilisedData);
                        }

                        byte[] Packet = null;

                        using (MemoryStream packetStream = new MemoryStream())
                            using (BinaryWriter packetWriter = new BinaryWriter(packetStream))
                            {
                                packetWriter.Write(serilisedData.Length);
                                packetWriter.Write(serilisedData);
                                Packet = packetStream.ToArray();
                            }

                        NetworkSocket.BeginSend(Packet, 0, Packet.Length, SocketFlags.None, EndSend, null);
                    }
                    catch
                    {
                        //Not connected
                    }
                }
Example #7
0
 public static unsafe int WriteSocket(NetworkSocket socket, byte[] data, NetworkEndPoint endPoint)
 {
     if (data == null)
         throw new ArgumentNullException(nameof(data));
     fixed(byte *ptr = data)
     return(Internal_WriteSocket(ref socket, ptr, (uint)data.Length, &endPoint));
 }
Example #8
0
 public static unsafe int ReadSocket(NetworkSocket socket, byte[] buffer, NetworkEndPoint endPoint)
 {
     if (buffer == null)
         throw new ArgumentNullException(nameof(buffer));
     fixed(byte *ptr = buffer)
     return(Internal_ReadSocket(ref socket, ptr, (uint)buffer.Length, &endPoint));
 }
Example #9
0
        public void Listen(int backlog = 100)
        {
            NetworkSocket.Bind(ServerSettings.ServerEndPoint);
            NetworkSocket.Listen(backlog);

            Begin(NetworkSocket);
        }
Example #10
0
    public void OnExit()
    {
        NetworkSocket.UnregisterOnConnectionEstablishedCallback(OnConnection);

        NetworkHandlers.Clear();
        InputHandlers.Clear();
    }
Example #11
0
 public void Init()
 {
     Handlers                 = new HandlersManager();
     MatchServerIPs           = new Dictionary <int, string>();
     DisconnectedMatchServers = new List <int>();
     NetworkSocket.RegisterOnDisconnectionCallback(OnDisconnection);
 }
Example #12
0
        private void InternalReceive(IAsyncResult ar)
        {
            SocketError se    = SocketError.SocketError;
            int         bytes = NetworkSocket?.EndReceive(ar, out se) ?? 0;

            if (se != SocketError.Success)
            {
                Disconnect(new SocketException());
                return;
            }

            byte[] packet = _defragger.Process(bytes);

            ReceiveWithDefragger();

            if (packet == null)
            {
                return;
            }
            try {
                IPacket pack = Packager.Unpack(packet, PackagingConfiguration);
                _receiveCallback(this, pack);
            } catch (Exception ex) {
                Disconnect(ex);
                return;
            }
        }
        public async void Client_RequestedStreamRead(object sender, NetworkSocket.RequestStreamReadArgs args)
        {
            NetworkSocket client = sender as NetworkSocket;

            byte[] buff      = new byte[args.ReadLen];
            int    bytesRead = 0;

            //We need to determine if localhost is the host of the files, otherwise we need to forward the request
            //onto the host of the files
            if (DoesTokenExist(args.Token))
            {
                try
                {
                    bytesRead = await ReadStream(args.Token, args.File, buff, 0, args.ReadLen);
                }
                catch (Exception ex)
                {
                    ISLogger.Write("Failed to read stream: " + ex.Message);
                    ISLogger.Write(ex.StackTrace);
                    client.SendFileErrorResponse(args.NetworkMessageId, "An error occurred while reading from stream: " + ex.Message);

                    return;
                }
            }

            if (bytesRead != buff.Length)
            {
                //resize the buffer so we don't send a buffer that ends with empty data.
                byte[] resizedBuffer = new byte[bytesRead];
                Buffer.BlockCopy(buff, 0, resizedBuffer, 0, bytesRead);
                buff = resizedBuffer;
            }

            client.SendReadRequestResponse(args.NetworkMessageId, buff);
        }
Example #14
0
        private void HandleReceve(IAsyncResult AR)
        {
            int packetSize = 0;

            try
            {
                packetSize = NetworkSocket.EndReceive(AR);
            }
            catch
            {
                OnDisconnect?.Invoke(this);
                return;
            }
            using (MemoryStream ms = new MemoryStream(PacketBuffer, 0, packetSize))
                using (BinaryReader br = new BinaryReader(ms))
                {
                    while (ms.Position != ms.Length)
                    {
                        int len = br.ReadInt32();

                        if (CurrentPacketLength == 0)
                        {
                            if (len <= 0)
                            {
                                NetworkSocket.BeginReceive(PacketBuffer, 0, PacketBuffer.Length, SocketFlags.None, RetrieveCallback, null);
                                return;
                            }

                            int cur = (int)(ms.Length - ms.Position);
                            if (cur >= len)
                            {
                                OnDataRetrieve?.Invoke(br.ReadBytes(len));
                            }
                            else
                            {
                                CurrentPacketLength = len;
                                PacketConstructor.Write(br.ReadBytes(cur), 0, cur);
                            }
                        }
                        else
                        {
                            int cur           = (int)(ms.Length - ms.Position);
                            int neededpackets = (int)(CurrentPacketLength - PacketConstructor.Length);
                            if (cur >= neededpackets)
                            {
                                PacketConstructor.Write(br.ReadBytes(neededpackets), 0, neededpackets);
                                OnDataRetrieve?.Invoke(PacketConstructor.ToArray());
                                PacketConstructor = new MemoryStream();
                            }
                            else
                            {
                                PacketConstructor.Write(br.ReadBytes(cur), 0, cur);
                            }
                        }
                    }
                }

            NetworkSocket.BeginReceive(PacketBuffer, 0, PacketBuffer.Length, SocketFlags.None, RetrieveCallback, null);
        }
Example #15
0
    public void Activate()
    {
        // Handlers

        NetworkHandlers.Add <AuthentificationMessage>(60000, OnAuthentificationRequestReceived);

        NetworkSocket.RegisterOnDisconnectionCallback(OnConnectionLost);
    }
Example #16
0
 // Callback when the ping method times out
 private void OnTimeOut(object state)
 {
     HasPingCommandTimedOut = true;
     if (NetworkSocket != null)
     {
         NetworkSocket.Close();
     }
 }
Example #17
0
        private static void KickPlayer(int index)
        {
            Console.WriteLine("Kicking Player index: " + index);
            ByteBuffer buffer = new ByteBuffer();

            buffer.WriteLong((long)ServerPackets.KICK);
            buffer.WriteLong(index);
            NetworkSocket.SendDataTo(0, buffer.ToArray());
        }
    public void Init()
    {
        Handlers            = new HandlersManager();
        KnownClients        = new Dictionary <string, ClientAccountInfo>(); // TODO : Ecrire une fonction pour charger cette liste à partir d'un fichier / base de données.
        OnlineClients       = new Dictionary <int, ClientAccountInfo>();
        DisconnectedClients = new List <int>();

        NetworkSocket.RegisterOnDisconnectionCallback(OnDisconnection);
    }
Example #19
0
        /// <summary>
        /// Uses defagger to receve packets.
        /// </summary>
        private void ReceiveWithDefragger()
        {
            NetworkSocket.BeginReceive(Defragger.ReceveBuffer, Defragger.BufferIndex, Defragger.BytesToReceve, SocketFlags.None, out SocketError SE, InternalReceve, null);

            if (SE != SocketError.Success)
            {
                Disconnect(new SocketException());
            }
        }
Example #20
0
        public void Shutdown()
        {
            Log.Information("Server socket closing...");
            NetworkSocket?.Shutdown("Server going down for quit");

            NetworkSocket    = null;
            NetworkPipe      = null;
            NetConfiguration = null;
        }
    public void SetUpServerConnection()
    {
        if (_networkSocket != null)
        {
            return;
        }

        _networkSocket = new NetworkSocket(SERVER_IP, SERVER_PORT, BUFFER_SIZE);
    }
        /// <summary>
        /// Shutdown the network client
        /// </summary>
        public void Shutdown()
        {
            Log.Information("stopping Client NetworkSocket...");
            NetworkSocket?.Shutdown("Client application exited");

            NetworkSocket    = null;
            NetConfiguration = null;
            MessagePipe      = null;
        }
Example #23
0
 public void Dispose()
 {
     if (NetworkSocket.Connected)
     {
         NetworkSocket.Shutdown(SocketShutdown.Both);
         NetworkSocket.Disconnect(true);
     }
     NetworkSocket.Close(1000);
 }
Example #24
0
        public void StartRetrieve()
        {
            if (RetrieveCallback != null)
            {
                return;
            }

            RetrieveCallback = new AsyncCallback(HandleReceve);
            NetworkSocket.BeginReceive(PacketBuffer, 0, PacketBuffer.Length, SocketFlags.None, RetrieveCallback, null);
        }
Example #25
0
 public void Disconnect()
 {
     try
     {
         NetworkSocket.Close();
     }
     catch
     {
     }
 }
Example #26
0
 public void Disconnect(Exception ex)
 {
     if (NetworkSocket != null)
     {
         NetworkSocket.Shutdown(SocketShutdown.Both);
         NetworkSocket.Dispose();
         NetworkSocket = null;
         OnDisconnect?.Invoke(this, ex);
     }
 }
Example #27
0
            public void Reception()
            {
                int  recHostID;
                int  recConnectionID;
                int  recChannelID;
                int  recSize;
                byte error;

                byte[] buffer = new byte[STANDARD_BUFFER_SIZE];

                NetworkEventType e;

                e = NetworkTransport.Receive(out recHostID, out recConnectionID, out recChannelID, buffer, STANDARD_BUFFER_SIZE, out recSize, out error);
                if (error != 0)
                {
                    if ((NetworkError)error == NetworkError.MessageToLong)
                    {
                        // Re-recevoir le message avec un buffer plus grand.
                        buffer = new byte[FRAGMENTED_BUFFER_SIZE];
                        e      = NetworkTransport.Receive(out recHostID, out recConnectionID, out recChannelID, buffer, FRAGMENTED_BUFFER_SIZE, out recSize, out error);
                    }
                    else
                    {
                        Debugger.Log("ERREUR - NETWORKRECEIVER - RECEPTION() - " + (NetworkError)error);
                    }
                }

                switch (e)
                {
                case (NetworkEventType.ConnectEvent):
                    Debugger.Log("Connexion établie. ID = " + recConnectionID);
                    NetworkSocket.OnConnectionEstablished(recConnectionID);
                    break;

                case (NetworkEventType.DisconnectEvent):
                    Debugger.Log("Connexion fermée. ID = " + recConnectionID);
                    NetworkSocket.OnDisconnection(recConnectionID);
                    break;

                case (NetworkEventType.DataEvent):

                    // Des données ont été reçues. D'abord, construire l'objet ReceivedMessage en reconstituant le NetworkMessage :
                    MemoryStream    stream = new MemoryStream(buffer);
                    object          info   = Formatter.Deserialize(stream);
                    ReceivedMessage msg    = new ReceivedMessage((NetworkMessage)info);
                    // Ensuite, remplir l'objet NetworkMessageInfo de msg :
                    msg.RecInfo.ConnectionID = recConnectionID;

                    //_____________________________________________________
                    // Enfin, envoyer le ReceivedMessage au MessageReader.

                    MessageReader.AddMessageToQueue(msg);
                    break;
                }
            }
        public void StartListen()
        {
            Logger.Info("Starting service...");

            IPEndPoint endPoint = GetLocalEndPoint();

            NetworkSocket.Bind(endPoint);
            NetworkSocket.Listen(_backlog);

            StartAccept();
        }
Example #29
0
    string Password; // Mot de passe qu'on tente d'utiliser.

    // FONCTIONS DE CLIENTSTATE
    public void OnEntry()
    {
        if (BloodAndBileEngine.WorldState.Map.Maps == null)
        {
            BloodAndBileEngine.WorldState.Map.LoadMaps();
        }
        InputHandlers.Add("Login", Login);
        InputHandlers.Add("LoginToMatchServer", LoginToMatchServer); // Permet de rapidement tester le Match Server (et surtout de ne pas avoir besoin de lancer un Master Server.)
        NetworkSocket.RegisterOnConnectionEstablishedCallback(OnConnection);

        NetworkHandlers.Add <BloodAndBileEngine.Networking.NetworkMessages.ConditionCheckResponseMessage>(60001, OnAuthentificationResponse);
    }
        public void OnAuthorization(NetworkSocket.Fast.ActionContext filterContext)
        {
            var valid = filterContext.Session.TagData.TryGet<bool>("Logined");
            if (valid == false)
            {
                // 直接关闭客户端的连接
                // filterContext.Session.Close();

                // 以异常方式提示客户端
                throw new Exception("未登录就尝试请求其它服务");
            }
        }
Example #31
0
        public static bool InitializeEngine()
        {
            NetworkSocket.Initialize();

            try {
                background            = new EngineObject($"{Common.Configuration.GamePath}/Data/background.png", 1024, 768);
                background.Size       = new Size2(1024, 768);
                background.SourceRect = new Rectangle(0, 0, 1024, 720);


                DataManager.Initialize();

                WindowTalent.Initialize();
                WindowSkill.Initialize();
                WindowPin.Initialize();
                WindowCash.Initialize();
                WindowMail.Initialize();
                WindowSelectedItem.Initialize();
                WindowViewTalent.Initialize();

                //Carrega os dados de classe.
                ClasseManager.Initialize();

                //Carrega os dados de npc.
                NpcManager.OpenData();

                //Carrega os dados de experiencia
                ExperienceManager.Read();

                EngineFont.Initialize();
                EngineMessageBox.Initialize();
                EngineInputBox.Initialize();
                EngineMultimedia.Initialize();

                WindowLogin.Initialize();
                WindowServer.Initialize();
                WindowCharacter.Initialize();
                WindowNewCharacter.Initialize();

                WindowGame.Initialize();

                WindowViewItem.Initialize();

                //    EngineMultimedia.PlayMusic(0, true);

                GameState = 1;
                return(true);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
Example #32
0
        /// <summary>
        /// 收到http请求
        /// </summary>
        /// <param name="context">上下文</param>
        /// <param name="requestContext">请求上下文</param>
        protected override void OnHttpRequest(IContenxt context, NetworkSocket.Http.RequestContext requestContext)
        {
            var request = requestContext.Request;
            var response = requestContext.Response;

            if (AppConfig.PathPattern.IsMatch(request.Path) == false)
            {
                var message = "路径不匹配,数据未转发 ..";
                response.Write(message);
                Console.WriteLine(message);
            }
            else
            {
                var fastSessions = context.AllSessions.FilterWrappers<FastSession>().ToArray();
                foreach (var session in fastSessions)
                {
                    this.PushRequest(session, request);
                }

                var message = string.Format("数据已转发到{0}到客户端 ..", fastSessions.Length);
                response.Write(message);
                Console.WriteLine(message);
            }
        }