/// <summary>
        /// Begins an operation to accept a connection request from the client
        /// </summary>
        /// <param name="e">The context object to use when issuing the accept operation on the server's listening socket</param>
        private void StartAccept(SocketAsyncEventArgs e)
        {
            if (e == null)
            {
                e            = new SocketAsyncEventArgs();
                e.Completed += (sender, completedE) => AcceptCompleted(completedE);
            }
            else
            {
                // socket must be cleared since the context object is being reused
                e.AcceptSocket = null;
            }

            _connectionLimit.WaitOne();
            try
            {
                if (MainSocket.AcceptAsync(e) == false)
                {
                    AcceptCompleted(e);
                }
            }
            catch (ObjectDisposedException)
            {
                // ignored
            }
        }
Ejemplo n.º 2
0
        public async void Start()
        {
            Logger.Warning("The CSF Discord Bot Core is a really unstable early version!");
            GatewayGetter gg = new GatewayGetter(token);

            try {
                Logger.Info("Requesting Gateway data...");
                GatewayGetter.GatewayResponse response = gg.GetGateway();
                Uri u = new Uri(response.url + "?format=json");

                int shard_count = response.shards;

                for (int i = 0; i < shard_count; i++)
                {
                    MainSocket socket = new MainSocket(u, token, i, shard_count);
                    foreach (Processor p in processors)
                    {
                        p.SetToken(token);
                        p.SetClient(this);
                        socket.AddProcessor(p);
                    }
                    shards.Add(socket);
                }

                foreach (MainSocket ms in shards)
                {
                    await ms.Connect();
                }

                started = true;
            } catch (Exception e) {
                Logger.Error($"Server startup failed: {e.Message}");
            }
        }
Ejemplo n.º 3
0
 public void Dispose()
 {
     if (MainSocket != null)
     {
         MainSocket.Close();
     }
 }
Ejemplo n.º 4
0
        private void Reconnect(object state)
        {
            lock (_sync)
            {
                try
                {
                    var now = DateTimeOffset.Now;

                    if (!IsConnected)
                    {
                        if ((now - _lastConnected).TotalSeconds > 5)
                        {
                            Start(true);
                        }
                    }
                    else if (_lastPing > _lastPong && (now - _lastPong).TotalSeconds > 20)
                    {
                        MainSocket?.Close();
                    }
                    else if ((now - _lastPing).TotalSeconds > 5)
                    {
                        _lastPing = DateTimeOffset.Now;
                        MainSocket.C2S_KeepAlive();
                    }
                }
                catch { }
                finally
                {
                    _reconnectTimer.Change(100, Timeout.Infinite);
                }
            }
        }
Ejemplo n.º 5
0
        public DDD_StatusComponent(MainSocket mainSocketIn)
        {
            handler     = new DDD_StatusComponentHandler(mainSocketIn);
            DataContext = handler.status;
            InitializeComponent();

            TestComponent.Content = handler.testComponent;
        }
Ejemplo n.º 6
0
        public DDD_tboxdtComponent(MainSocket mainSocketIn, bool isSoraIn)
        {
            handler     = new DDD_tboxdtHandler(mainSocketIn, isSoraIn);
            DataContext = handler.file;
            InitializeComponent();

            TestComponent.Content = handler.testComponent;
        }
Ejemplo n.º 7
0
        public DDD_lboardComponent(MainSocket mainSocketIn)
        {
            handler     = new DDD_lboardHandler(mainSocketIn);
            DataContext = handler;
            InitializeComponent();

            TestComponent.Content = handler.testComponent;
        }
        public DDD_itemdataComponent(MainSocket mainSocketIn)
        {
            handler     = new DDD_itemdataHandler(mainSocketIn);
            DataContext = handler.file;
            InitializeComponent();

            TestComponent.Content = handler.testComponent;
        }
Ejemplo n.º 9
0
 public void Stop()
 {
     lock (_sync)
     {
         _reconnectTimer.Change(Timeout.Infinite, Timeout.Infinite);
         MainSocket?.Close();
     }
 }
Ejemplo n.º 10
0
        public DDD_techprmComponent(MainSocket mainSocketIn, bool isPlayerIn)
        {
            handler     = new DDD_techprmHandler(mainSocketIn, isPlayerIn);
            DataContext = handler;
            InitializeComponent();

            TestComponent.Content = handler.testComponent;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Disconnects the client from any established connections.
        /// </summary>
        public void Disconnect()
        {
            var noDelay = MainSocket.NoDelay;

            MainSocket.Dispose();
            MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = noDelay
            };
        }
Ejemplo n.º 12
0
 private void Connect(string remoteAddress, int remotePort)
 {
     try
     {
         MainSocket.BeginConnect(remoteAddress, remotePort, OnConnect, null);
     }
     catch (Exception ex)
     {
         FireException(ExceptionType.Connect, ex.Message);
     }
 }
Ejemplo n.º 13
0
 private void Accept(int localPort)
 {
     try
     {
         MainSocket.BeginAccept(OnAccept, localPort);
     }
     catch (Exception ex)
     {
         FireException(ExceptionType.Accept, ex.Message);
     }
 }
Ejemplo n.º 14
0
 public MainTestSocketed(MainSocket mainSocketIn, Enums.ProcessType procType, bool readOn, bool writeOn, bool exportOn)
 {
     mainSocket = mainSocketIn;
     try
     {
         testComponent = new TestComponent(procType, this, readOn, writeOn, exportOn);
     }
     catch (Exception e)
     {
         mainSocket.writeInfoLabel("Couldn't hook to process. Make sure the app is running in admin mode if the game is.");
     }
 }
Ejemplo n.º 15
0
        // CONSTRUCTORS

        public DDD_techprmHandler(MainSocket mainSocketIn, bool isPlayerIn) : base(mainSocketIn, Enums.ProcessType.DDD_EGS)
        {
            file     = new DDD_techprm_File();
            isPlayer = isPlayerIn;
            if (isPlayer)
            {
                fileAddress = (long)DDD_Pointers.TECHPRMP_MOD_EGS;
            }
            else
            {
                fileAddress = (long)DDD_Pointers.TECHPRM_MOD_EGS;
            }
        }
Ejemplo n.º 16
0
 private void OnConnect(IAsyncResult ar)
 {
     try
     {
         MainSocket.EndConnect(ar);
         FireConnect();
         Receive();
     }
     catch (Exception ex)
     {
         FireException(ExceptionType.Connect, ex.Message);
     }
 }
Ejemplo n.º 17
0
        protected override void OnClose(TSession session, SocketCloseReason reason)
        {
            MainSocket.Close();

            TSession sessOut;

            // If the session is null, the connection timed out while trying to connect.
            if (session != null)
            {
                ConnectedSessions.TryRemove(Session.Id, out sessOut);
            }

            base.OnClose(session, reason);
        }
Ejemplo n.º 18
0
 private void OnAccept(IAsyncResult ar)
 {
     try
     {
         int       localPort      = (int)ar.AsyncState;
         Socket    acceptedSocket = MainSocket.EndAccept(ar);
         NetSocket netSocket      = new NetSocket(acceptedSocket, BufferLength);
         FireAccept(netSocket);
         Accept(localPort);
     }
     catch (Exception ex)
     {
         FireException(ExceptionType.Accept, ex.Message);
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Terminates this server and notify all connected clients.
        /// </summary>
        public void Stop()
        {
            if (_isStopped)
            {
                return;
            }
            TSession[] sessions = new TSession[ConnectedSessions.Values.Count];
            ConnectedSessions.Values.CopyTo(sessions, 0);

            foreach (var session in sessions)
            {
                session.Close(SocketCloseReason.ServerClosing);
            }

            MainSocket.Close();
            _isStopped = true;
        }
Ejemplo n.º 20
0
        // TODO: Add user list
        public static void OnUserConnect(IAsyncResult ar)
        {
            SausageConnection user;

            try
            {
                user = new SausageConnection(MainSocket.EndAccept(ar));
            }
            catch (SocketException ex)
            {
                Close();
                return;
            }
            catch (ObjectDisposedException ex)
            {
                return;
            }
            if (!Blacklisted.Any(x => x == user.Ip.Address))
            {
                UiCtx.Send(x => ConnectedUsers.Add(user));
                UiCtx.Send(x => Vm.ConnectedUsers = SortUsersList());
                UiCtx.Send(x => Vm.Messages.Add(new ServerMessage($"{user} has connected")));
                UiCtx.Send(x => Mw.AddTextToDebugBox($"User connected on {user.Ip}\n"));
                // global packet for all the users to know the user has joined
                PacketFormat GlobalPacket = new PacketFormat(PacketOption.UserConnected)
                {
                    Guid    = user.UserInfo.Guid,
                    NewName = user.UserInfo.Name
                };
                // local packet for the user (who joined) to get his GUID
                PacketFormat LocalPacket = new PacketFormat(PacketOption.GetGuid)
                {
                    Guid      = user.UserInfo.Guid,
                    UsersList = UsersDictionary.ToArray()
                };
                UsersDictionary.Add(user.UserInfo);
                user.SendAsync(LocalPacket);
                Log(GlobalPacket, user);
            }
            else
            {
                // doesn't log if the user is blacklisted
                user.Disconnect();
            }
            MainSocket.BeginAccept(OnUserConnect, null);
        }
Ejemplo n.º 21
0
 private void HandleNewExternalSocket(Socket socket)
 {
     Console.WriteLine($"New external socket from {socket.RemoteEndPoint}");
     if (MainSocket?.IsConnected ?? false)
     {
         var channel = CreateNewChannel(socket);
         try
         {
             MainSocket.S2C_StartNewConnection(channel.ChannelId, Mapping.TargetPort, Mapping.InternalPort);
         }
         catch (Exception ex)
         {
             socket.Close();
             channel.Close(ex);
         }
     }
 }
Ejemplo n.º 22
0
 public static void Close()
 {
     if (IsOpen)
     {
         MainSocket.Close();
         foreach (SausageConnection u in ConnectedUsers)
         {
             u.Disconnect();
         }
         UiCtx.Send(x => Vm.Messages = new ObservableCollection <IMessage>());
         UiCtx.Send(x => Vm.Messages.Add(new ServerMessage("Closed all sockets")));
         IsOpen = false;
     }
     else
     {
         MessageBox.Show("Server is already closed", "Sausage Server");
     }
 }
Ejemplo n.º 23
0
        private void HandleStartNewConnection(ProtocolSocket socket, int id, ushort targetPort, ushort internalPort)
        {
            Console.WriteLine($"HandleStartNewConnection #{id} target={targetPort} internal={internalPort}");
            var localSocket  = TryConnect(BoundInterface.ToString(), targetPort);
            var remoteSocket = TryConnect(RelayAddress, internalPort);
            var success      = localSocket != null && remoteSocket != null;

            if (IsConnected)
            {
                MainSocket.C2S_StartNewConnectionReply(id, internalPort, success);
            }
            var protoSocket = new ProtocolSocket(remoteSocket);

            protoSocket.C2S_StartRelay(id);
            var proxy = new ChannelProxy(localSocket);

            proxy.ChannelId = id;
            proxy.SetProxy(protoSocket);
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            int Port   = 9230;
            var server = new MainSocket(Port);

            // Intialize the hashes...
            ConquerHash = GetFileHash(@"Files\Conquer.exe");
            MagicHash   = GetFileHash(@"Files\ini\MagicEffect.ini");
            Console.WriteLine($"Socket is alive on port {Port}");
            Console.Title = $"Protection Server - {Port}";

            Console.WriteLine();
            new Thread(new ThreadStart(Protection)).Start();

            while (true)
            {
                Console.ReadLine();
            }
        }
Ejemplo n.º 25
0
 private void HandleNewSocket(Socket socket)
 {
     if (MainSocket == null || !MainSocket.IsConnected || (DateTimeOffset.Now - _lastPing).TotalSeconds > 15)
     {
         Console.WriteLine($"Replacing the old socket with one from {socket.RemoteEndPoint}");
         if (MainSocket != null)
         {
             MainSocket.Close();
         }
         _lastPing  = DateTimeOffset.Now;
         MainSocket = new ProtocolSocket(socket);
         MainSocket.C2S_OnStartNewConnectionReply = HandleConnectionReply;
         MainSocket.C2S_OnKeepAlive = HandleKeepAlive;
         MainSocket.Initialize();
     }
     else
     {
         socket.Close();
     }
 }
Ejemplo n.º 26
0
        private void Accept(IAsyncResult result)
        {
            HTTPSession WebSession;

            try
            {
                Socket AcceptedSocket = MainSocket.EndAccept(result);
                lock (SessionTable)
                {
                    WebSession               = new HTTPSession(LocalIPEndPoint, AcceptedSocket);
                    WebSession.OnClosed     += CloseSink;
                    WebSession.OnHeader     += HandleHeader;
                    WebSession.OnReceive    += HandleRequest;
                    SessionTable[WebSession] = WebSession;
                }
                SessionTimer.Add(WebSession, 3);
                OnSessionEvent.Fire(this, WebSession);
                WebSession.StartReading();
            }
            catch (Exception err)
            {
                if (err.GetType() != typeof(ObjectDisposedException))
                {
                    // Error
                    EventLogger.Log(err);
                }
            }

            try
            {
                MainSocket.BeginAccept(Accept, null);
            }
            catch (Exception ex)
            {
                EventLogger.Log(ex);
                // Socket was closed
            }
        }
        private void Accept(IAsyncResult result)
        {
            HTTPSession WebSession = null;

            try
            {
                Socket AcceptedSocket = MainSocket.EndAccept(result);
                lock (SessionTable)
                {
                    WebSession               = new HTTPSession(this.LocalIPEndPoint, AcceptedSocket);
                    WebSession.OnClosed     += new HTTPSession.SessionHandler(CloseSink);
                    WebSession.OnHeader     += new HTTPSession.ReceiveHeaderHandler(HandleHeader);
                    WebSession.OnReceive    += new HTTPSession.ReceiveHandler(HandleRequest);
                    SessionTable[WebSession] = WebSession;
                }
                SessionTimer.Add(WebSession, 3);
                OnSessionEvent.Fire(this, WebSession);
                WebSession.StartReading();
            }
            catch (Exception err)
            {
                if (err.GetType() != typeof(System.ObjectDisposedException))
                {
                    // Error
                    OpenSource.Utilities.EventLogger.Log(err);
                }
            }

            try
            {
                MainSocket.BeginAccept(new AsyncCallback(Accept), null);
            }
            catch (Exception ex)
            {
                OpenSource.Utilities.EventLogger.Log(ex);
                // Socket was closed
            }
        }
Ejemplo n.º 28
0
        // CONSTRUCTORS

        public DDD_tboxdtHandler(MainSocket mainSocketIn, bool isSoraIn) : base(mainSocketIn, Enums.ProcessType.DDD_EGS)
        {
            file        = new DDD_tboxdt_File();
            file.isSora = isSoraIn;
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Binds the socket to the specified address
 /// </summary>
 public void BindSocket(string ip, int port)
 {
     SetAddress(ip, port);
     MainSocket.Bind(_socketAddress);
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Begins listening for and accepting socket connections.
        /// </summary>
        /// <param name="backLog">Maximum amount of pending connections</param>
        public void Listen(int backLog = 25, int maximumConnections = 60)
        {
            _connections = new Connection[maximumConnections];

            var listenerThread = new Thread(() =>
            {
                int index = -1;

                if (_socketAddress == null)
                {
                    throw new Exception("You must specifiy the socket address before calling the listen method!");
                }
                if (!MainSocket.IsBound)
                {
                    throw new Exception("You must bind the socket before calling the listen method!");
                }

                MainSocket.Listen(backLog);

                Console.WriteLine("[NettyServer] Server listening on address: " + MainSocket.LocalEndPoint);

                while (true)
                {
                    var incomingSocket = MainSocket.Accept();

                    for (int i = 0; i < maximumConnections; i++)
                    {
                        if (_connections[i] == null)
                        {
                            _connections[i] = new Connection(incomingSocket, this)
                            {
                                Socket = { NoDelay = MainSocket.NoDelay }
                            };

                            index = i;
                            break;
                        }
                    }

                    Console.WriteLine("[NettyServer] Received a connection from: " + incomingSocket.RemoteEndPoint);

                    if (Handle_NewConnection != null)
                    {
                        Handle_NewConnection.Invoke(index);
                    }

                    try
                    {
                        Thread recThread = new Thread(x => BeginReceiving(incomingSocket, index));
                        recThread.Name   = incomingSocket.RemoteEndPoint + ": incoming data thread.";
                        recThread.Start();
                    }
                    catch (ObjectDisposedException)
                    {
                    }
                }
            })
            {
                Name = "NettyServer Incoming Connection Thread"
            };

            listenerThread.Start();
        }