Exemplo n.º 1
0
        // This is the call back function, which will be invoked when a client is connected
        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                Socket      clientSocket = ServerSocket.EndAccept(asyn);
                AsyncClient asyncClient  = new AsyncClient(clientSocket);
                Clients.Add(asyncClient);
                AsyncClientsDict.Add(clientSocket, asyncClient);

                ClientConnected(this, new ServerClientEventArgs(asyncClient));

                // Let the worker Socket do the further processing for the
                // just connected client
                WaitForData(clientSocket);
                // Now increment the client count

                // Since the main Socket is now free, it can go back and wait for
                // other clients who are attempting to connect
                ServerSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (Exception ex)
            {
                ServerException(this, new ExceptionEventArgs(ex));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Denne metode håndterer kommunikation mellem clienten og serverens på asynkron vis.
        /// </summary>
        public void AcceptCallback(IAsyncResult asyncResult)
        {
            //Her laves en lokal variable af typen socket, den deklareres her fordi at socketens scope skal persistere udenfor try catch kaldet lige under.
            Socket tempSocket;

            //Her forsøges der at placerer en client socket på lokal variablen.
            try {
                //Server socketen benytter sig at funktionen som opretter en socket instans som placeres på lokal variablen uden for try catchens scope.
                tempSocket = ServerSocket.EndAccept(asyncResult);
            }
            //Hvis objektet ikke længere eksisterer kastes objectdisposedexceptionen. I tilfælde af det ikke lykkedes at oprette en forbindelse på den lokale socket.
            catch (ObjectDisposedException x)
            //Denne exception bliver kastet når at der bliver forsøgt at blive gjort noget på et objekt som allerede er skillet af med.
            {
                Debug.WriteLine(x);
                return;
            }

            lock (ClientSocket) {
                //I dette kald bliver den nyoprettet client socket tilføjet til serverens clientsocket liste.
                ClientSocket.Add(tempSocket);
            }

            //Her begynder den nyoprettet socket at modtage information fra clientens socket.
            tempSocket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None
                                    /* TODO - Gå hjem og find ud af hvad singlecast og multicast er*/, ReceiveCallBack, tempSocket);
            Debug.WriteLine("Client forbundet, venter på input");

            //Serverens socket kalder beginaccept rekusivt for hele tiden at se om der er nye data og forbindelser mellem client socketen og serverens socket.
            ServerSocket.BeginAccept(AcceptCallback, null);
        }
Exemplo n.º 3
0
        //===================================================================================================================
        //===================================================================================================================
        //=         CALLBACK METHODS                                                                                        =
        //===================================================================================================================
        //===================================================================================================================

        #region -=[- CALLBACK METHODS -]=-

        /// <summary>
        /// Gets called when a new client connects.
        /// </summary>
        /// <param name="AR"></param>
        private void OnClientAccept(IAsyncResult AR)
        {
            Debug($"New client connected!", DebugParams);

            // Accept the client socket and add it to the socket-list
            Socket clientSocket = ServerSocket.EndAccept(AR);

            LClients.Add(new NetComClientData(clientSocket));
            clientSocket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(OnClientReceive), clientSocket);

            // Re-Open the server-socket for further connections
            Start();
        }
Exemplo n.º 4
0
 /// <summary>
 /// Метод асинхронного принятия новых подключений
 /// </summary>
 /// <param name="result"></param>
 private void AcceptCallback(IAsyncResult result)
 {
     lock (locker)
     {
         if (IsListeningStatus != false)
         {
             ConnectionValue connection = new ConnectionValue();
             try
             {
                 // Завершение операции Accept
                 connection.Socket     = ServerSocket.EndAccept(result);
                 connection.SocketID   = connection.Socket.Handle;
                 connection.Buffer     = new byte[SizeBuffer];
                 connection.RemoteIP   = ((IPEndPoint)connection.Socket.RemoteEndPoint).Address.ToString();
                 connection.RemotePort = ((IPEndPoint)connection.Socket.RemoteEndPoint).Port;
                 lock (Сonnections) Сonnections.Add(connection);
                 // Начало операции Receive и новой операции Accept
                 connection.Socket.BeginReceive(connection.Buffer,
                                                0, connection.Buffer.Length, SocketFlags.None,
                                                new AsyncCallback(ReceiveCallback),
                                                connection);
                 //Сообщаем о новом подключении
                 CallConnected(connection);
             }
             catch (SocketException exc)
             {
                 CallErrorServer(Sockets.ServerErrorType.AcceptError, exc.Message + exc.ToString());
                 CloseConnection(connection);
             }
             catch (Exception exc)
             {
                 CallErrorServer(Sockets.ServerErrorType.AcceptError, exc.Message + exc.ToString());
                 CloseConnection(connection);
             }
             finally
             {
                 try
                 {
                     if (ServerSocket != null && ServerSocket.IsBound)
                     {
                         ServerSocket?.BeginAccept(new AsyncCallback(AcceptCallback), null);
                     }
                 }
                 catch (Exception ex)
                 {
                     CallErrorServer(Sockets.ServerErrorType.AcceptError, ex.Message + ex.ToString());
                 }
             }
         }
     }
 }
        private void OnAcceptCallback(IAsyncResult ar)
        {
            try
            {
                if (ServerSocket is null)
                {
                    throw new ArgumentException("Socket is null");
                }
                var client = ServerSocket.EndAccept(ar);
                OnReportingStatus(StatusCode.Success, $"Successfully accepted new TCP connection");

                if (Clients.Count >= _maxClientsQueue)
                {
                    OnReportingStatus(StatusCode.Error,
                                      $"Rejected next pending TCP connection. Accepted clients count: {Clients.Count} >= Maximum count of clients: {_maxClientsQueue}");
                    client.Send(Encoding.UTF8.GetBytes("Rejected connection"));
                    client.Shutdown(SocketShutdown.Both);
                    client.Close(1000);
                }
                else
                {
                    var handler   = new Client(client, true);
                    var whoAreYou = handler.WhoAmI;
                    OnNewClient(whoAreYou.Id, whoAreYou.Ip, whoAreYou.ServerIp);
                    RegisterHandler(handler);
                    lock (Lock)
                    {
                        Clients.Add(handler);
                    }
                }

                AcceptNextPendingConnection();
            }
            catch (ObjectDisposedException)
            {
            }
            catch (SocketException socketException)
            {
                OnCaughtException(socketException, EventCode.Accept);
            }
            catch (ArgumentException argumentException)
            {
                OnCaughtException(argumentException, EventCode.Accept);
            }
            catch (Exception exception)
            {
                OnCaughtException(exception, EventCode.Other);
            }
        }
Exemplo n.º 6
0
        private void OnAccept(IAsyncResult ar)
        {
            Socket sock = ServerSocket.EndAccept(ar);

            Sock.Client client = new Sock.Client(sock, DataBuffer.Length);
            client.EncryptionKey      = EncryptionKey;
            client.EncryptionSettings = EncryptionSettings;
            client.UseEncryption      = UseEncryption;

            if (OnClientAccepted != null)
            {
                OnClientAccepted(client);
            }

            client.ClientSocket.BeginReceive(DataBuffer, 0, DataBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), client);

            ServerSocket.BeginAccept(new AsyncCallback(OnAccept), sock);
        }
Exemplo n.º 7
0
        private void AcceptCallback(IAsyncResult ar)
        {
            Socket socket;

            try
            {
                socket = ServerSocket.EndAccept(ar);
            }
            catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
            {
                return;
            }

            ClientSockets.Add(socket);
            socket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket);
            // Console.WriteLine("Client connected, waiting for request...");
            ClientConnected?.Invoke();
            ServerSocket.BeginAccept(AcceptCallback, null);
        }
Exemplo n.º 8
0
        private void AcceptCallback(IAsyncResult AR)
        {
            lock (lockAccept)
            {
                Socket socket;

                try
                {
                    socket = ServerSocket.EndAccept(AR);
                    var session = new SocketSession(socket, BufferSize);

                    ClientSockets.Add(session);

                    socket.BeginReceive(session.SessionStorage, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket);
                    ServerSocket.BeginAccept(AcceptCallback, null);
                }
                catch (Exception ex) // I cannot seem to avoid this (on exit when properly closing sockets)
                {
                    LogController.WriteLog(new ServerLog("*** ERROR ***: \n" + ex.Message, ServerLogType.ERROR));
                }
            }
        }
Exemplo n.º 9
0
        // callbacks...
        private void AcceptCallback(IAsyncResult results)
        {
            Socket socket;

            try
            {
                socket = ServerSocket.EndAccept(results);
            }
            catch (ObjectDisposedException)
            {
                // I cannot seem to avoid this (on exit when properly closing sockets)
                return;
            }

            this.ConnectedSockets.Add(socket);

            socket.BeginReceive(this.Buffer, 0, CommunicationProperties.PackageSize,
                                SocketFlags.None, this.ReceiveCallback, socket);

            Console.WriteLine("Client connected, waiting for request...");

            this.ServerSocket.BeginAccept(AcceptCallback, null);
        }
Exemplo n.º 10
0
 private void OnAcceptCallback(IAsyncResult ar)
 {
     try
     {
         if (ServerSocket is null)
         {
             throw new ArgumentException("Socket is null");
         }
         var client = ServerSocket.EndAccept(ar);
         OnReportingStatus(StatusCode.Success, $"Successfully accepted new TCP connection");
         var handler   = new Client(client, true);
         var whoAreYou = handler.WhoAmI;
         OnNewClient(whoAreYou.Id, whoAreYou.Ip, whoAreYou.ServerIp);
         CleanClients();
         RegisterHandler(handler);
         lock (Lock)
         {
             Clients.Add(handler);
         }
     }
     catch (ObjectDisposedException)
     {
     }
     catch (SocketException socketException)
     {
         OnCaughtException(socketException, EventCode.Accept);
     }
     catch (ArgumentException argumentException)
     {
         OnCaughtException(argumentException, EventCode.Accept);
     }
     catch (Exception exception)
     {
         OnCaughtException(exception, EventCode.Other);
     }
 }
Exemplo n.º 11
0
        private void ClientJoined(IAsyncResult ar)
        {
            try
            {
                ServerSocket = (Socket)ar.AsyncState;
                T client = (T)Activator.CreateInstance(typeof(T), ServerSocket.EndAccept(ar));

                client.OnClientDisconnected += () =>
                {
                    OnClientLeaved?.Invoke(client);
                    Clients.Remove(client);
                };

                OnClientJoined?.Invoke(client);
                client.Receive();

                Clients.Add(client);
                AcceptClient();
            }
            catch (Exception e)
            {
                OnErrorHandled?.Invoke(e);
            }
        }