Exemple #1
0
        private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    //todo: else branch can be used with min dependency NET46
#if NET452 || NET461
                    var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
#else
                    var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);
#endif

                    var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, null), new MqttPacketSerializer(), _logger);
                    ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
                }
                catch (ObjectDisposedException)
                {
                    // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
                }
                catch (Exception exception)
                {
                    if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
                    {
                        return;
                    }

                    _logger.Error <MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemple #2
0
        private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
#if NET452
                    var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
#else
                    var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
#endif

                    var sslStream = new SslStream(new NetworkStream(clientSocket));
                    await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);

                    var clientAdapter = _communicationAdapterFactory.CreateServerCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream));
                    ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
                }
                catch (Exception exception)
                {
                    _logger.LogError(new EventId(), exception, "Error while accepting connection at TLS endpoint.");

                    //excessive CPU consumed if in endless loop of socket errors
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemple #3
0
        public void ReadCallback(IAsyncResult ar)
        {
            string      content   = string.Empty;
            StateObject state     = (StateObject)ar.AsyncState;
            Socket      handler   = state.workSocket;
            int         bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
                content = state.sb.ToString();
                if (content.IndexOf("<!Nickname>") > -1)
                {
                    Client client = new Client(connectionsCounter, handler, content.Replace("<!Nickname>", ""));
                    ClientAccepted.Invoke(this, new ClientAcceptedEventArgs(client));
                    connectionsCounter++;
                }
                else if (content.IndexOf("<!Message>") > -1)
                {
                    MessageRecieved.Invoke(this, new MessageRecievedEventArgs(new Message(messagesCounter, MessageType.TextMessage, Encoding.UTF8.GetBytes(content))));
                    messagesCounter++;
                }
                else
                {
                    return;
                }
            }
        }
Exemple #4
0
        private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
#if NET452 || NET461
                    var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
#else
                    var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
#endif

                    var sslStream = new SslStream(new NetworkStream(clientSocket));
                    await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);

                    var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer(), _logger);
                    ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
                }
                catch (ObjectDisposedException)
                {
                    // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
                }
                catch (Exception exception)
                {
                    if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
                    {
                        return;
                    }

                    _logger.Error <MqttServerAdapter>(exception, "Error while accepting connection at TLS endpoint.");
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemple #5
0
 protected virtual void NetClientAccepted()
 {
     //NetClient.SendMessage(new MsgWantWHash());
     if (ClientAccepted != null)
     {
         ClientAccepted.Invoke(this, EventArgs.Empty);
     }
 }
Exemple #6
0
        public void AcceptTcpClient(IAsyncResult ar)
        {
            TcpClient tcpClient = _listener.EndAcceptTcpClient(ar);

            _listener.BeginAcceptTcpClient(AcceptTcpClient, null);

            ClientAccepted?.Invoke(new Client(tcpClient));
        }
Exemple #7
0
        private void ServerSokcet_OnAccepted(object cci)
        {
            var ci = (ChannelInfo)cci;

            if (ci != null)
            {
                var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(ci.ClientSocket, ci.Stream), new MqttPacketSerializer(), _logger);

                ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
            }
        }
Exemple #8
0
        private void ServerSokcet_OnAccepted(string id)
        {
            var ci = ChannelManager.Current.Get(id);

            if (ci != null)
            {
                var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(ci.ClientSocket, ci.Stream), new MqttPacketSerializer(), _logger);

                ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
            }
        }
Exemple #9
0
 private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     try
     {
         var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(args.Socket), new MqttPacketSerializer(), _logger);
         ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
     }
     catch (Exception exception)
     {
         _logger.Error <MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
     }
 }
 private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     try
     {
         var clientAdapter = _communicationAdapterFactory.CreateServerCommunicationAdapter(new MqttTcpChannel(args.Socket));
         ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
     }
     catch (Exception exception)
     {
         _logger.LogError(new EventId(), exception, "Error while accepting connection at default endpoint.");
     }
 }
 private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     try
     {
         var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(args.Socket), new MqttPacketSerializer());
         ClientAccepted?.Invoke(clientAdapter);
     }
     catch (Exception exception)
     {
         MqttNetTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at default endpoint.");
     }
 }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            var serializer = new MqttPacketSerializer();

            using (var adapter = new MqttConnectionContext(serializer, connection))
            {
                var args = new MqttServerAdapterClientAcceptedEventArgs(adapter);
                ClientAccepted?.Invoke(this, args);

                await args.SessionTask;
            }
        }
Exemple #13
0
        /// <summary>
        /// Loop to accept and register clients
        /// </summary>
        /// <returns></returns>
        private async Task waitingForClients()
        {
            while (isWorking)
            {
                var socket = await _listener.AcceptTcpClientAsync();

                if (socket != null && socket.Connected)
                {
                    var client = new EEClient(socket);
                    ClientAccepted?.Invoke(client);
                }
            }
        }
        private void AddClient(TcpClient tcpClient)
        {
            int calculatedId = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).GetHashCode();

            Debugger.Log(1, null, $"{nameof(SimpleServer)}: Client {((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString()} accepted from the server. Id will be {calculatedId}\n");

            if (!Clients.ContainsKey(calculatedId))
            {
                Clients.Add(calculatedId, CreateInitializedClient(calculatedId));
            }
            Clients[calculatedId].SetConnection(tcpClient);
            SendServerAssignedId(calculatedId);
            ClientAccepted?.Invoke(this, Clients[calculatedId]);
        }
        public Task AcceptWebSocketAsync(WebSocket webSocket)
        {
            if (webSocket == null)
            {
                throw new ArgumentNullException(nameof(webSocket));
            }

            var channel       = new MqttWebSocketServerChannel(webSocket);
            var clientAdapter = _mqttCommunicationAdapterFactory.CreateServerCommunicationAdapter(channel);

            var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);

            ClientAccepted?.Invoke(this, eventArgs);
            return(eventArgs.SessionTask);
        }
Exemple #16
0
        public Task AcceptWebSocketAsync(WebSocket webSocket)
        {
            if (webSocket == null)
            {
                throw new ArgumentNullException(nameof(webSocket));
            }

            var channel       = new MqttWebSocketServerChannel(webSocket);
            var clientAdapter = new MqttChannelAdapter(channel, new MqttPacketSerializer(), new MqttNetLogger());

            var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);

            ClientAccepted?.Invoke(this, eventArgs);
            return(eventArgs.SessionTask);
        }
Exemple #17
0
        private async void DoFetchClients()
        {
            try {
                while (Started)
                {
                    var tcpClient = await Task.Run(() => Listener.AcceptTcpClientAsync(), _cancelSource.Token);

                    var vrClient = new TypedTcpClient <TData>(tcpClient, _serializer);
                    ClientAccepted?.Invoke(this, vrClient);
                }
            } finally {
                Listener.Stop();
            }

            _cancelSource.Cancel();
        }
Exemple #18
0
        public void AcceptOnClient()
        {
            Socket     clientSocket = _serverSocket.Accept();
            ClientData clientData   = new ClientData
            {
                ClientId      = (int)clientSocket.Handle,
                ClientSocket  = clientSocket,
                NetworkStream = new NetworkStream(clientSocket, FileAccess.ReadWrite)
            };


            Clients.Add((int)clientSocket.Handle, clientData);

            clientData.Reader = new StreamReader(clientData.NetworkStream);
            clientData.Writer = new StreamWriter(clientData.NetworkStream);
            ClientAccepted?.Invoke(this, (int)clientSocket.Handle);
        }
        private async Task AcceptClientConnectionsAsync()
        {
            while (!_cancellationToken.IsCancellationRequested)
            {
                try
                {
#if NET452 || NET461
                    var clientSocket = await Task.Factory.FromAsync(_socket.BeginAccept, _socket.EndAccept, null).ConfigureAwait(false);
#else
                    var clientSocket = await _socket.AcceptAsync().ConfigureAwait(false);
#endif
                    clientSocket.NoDelay = true;

                    SslStream sslStream = null;

                    if (_tlsCertificate != null)
                    {
                        sslStream = new SslStream(new NetworkStream(clientSocket), false);
                        await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, _tlsOptions.SslProtocol, false).ConfigureAwait(false);
                    }

                    _logger.Verbose("Client '{0}' accepted by TCP listener '{1}, {2}'.",
                                    clientSocket.RemoteEndPoint,
                                    _socket.LocalEndPoint,
                                    _addressFamily == AddressFamily.InterNetwork ? "ipv4" : "ipv6");

                    var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer(), _logger);
                    ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
                }
                catch (ObjectDisposedException)
                {
                    // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
                }
                catch (Exception exception)
                {
                    if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
                    {
                        return;
                    }

                    _logger.Error(exception, $"Error while accepting connection at TCP listener {_socket.LocalEndPoint} TLS={_tlsCertificate != null}.");
                    await Task.Delay(TimeSpan.FromSeconds(1), _cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemple #20
0
        public async Task RunWebSocketConnectionAsync(WebSocket webSocket, string endpoint)
        {
            if (webSocket == null)
            {
                throw new ArgumentNullException(nameof(webSocket));
            }

            var clientAdapter = new MqttChannelAdapter(new MqttWebSocketChannel(webSocket, endpoint), new MqttPacketSerializer(), new MqttNetLogger().CreateChildLogger(nameof(MqttWebSocketServerAdapter)));

            var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);

            ClientAccepted?.Invoke(this, eventArgs);

            if (eventArgs.SessionTask != null)
            {
                await eventArgs.SessionTask.ConfigureAwait(false);
            }
        }
        //Метод обработки конкретного клиента
        private async Task HandleClient(TcpClient client)
        {
            //Оборачиваем TcpClient в наш собственный класс RemoteClient
            //Сделано для сопоставления TCP соединения и нашей моделей пользователя
            //Чтобы понимать, по какому соединению необходимо отправлять данные
            RemoteClient remoteClient = new RemoteClient(
                //Аргументом является функция отправки сообщения
                //Этому клиенту. Мы и пишем, что при отправке сообщения
                //Этому клиенту надо отправить данное сообщение именно на этот client
                R => SendResponseToClient(R, client));

            //Вызываем событие о том, что клиент присоединился.
            //Так внешний код сможет узнать о том, что подсоединился новый клиент
            //И начать следить ща его действиями
            ClientAccepted?.Invoke(remoteClient);
            //Пока не отменили работу
            while (!cancellationToken.IsCancellationRequested)
            {
                //Буффер для хранения длины сообщения
                var messageLength = new byte[4];
                //Буффер для хранения самого сообщения
                var buffer = new byte[4096];
                //Читаем 4 байта, представляющие длину сообщения
                await client.GetStream().ReadAsync(messageLength, 0, 4);

                //Преобразуем эти 4 байта в число
                var length = BitConverter.ToInt32(messageLength, 0);
                //Читаем все сообщение в спец буффер для сообщения
                //Читаем именно нужное нам колчество денег
                await client.GetStream().ReadAsync(buffer, 0, length);

                //Получаем из считанныз байт саму строку JSON
                //которую нам прислал клиент
                var jsonString = Encoding.UTF8.GetString(buffer, 0, length);
                //Разбираем строку и кладем все данные в JToken
                var token = JToken.Parse(jsonString);
                //Выводим сообщение  о том, что мы получили некое сообщение
                Console.WriteLine("Received message");
                //Уведомляем клиента о том, что пришло новое сообщение
                remoteClient.Notify(token);
            }
        }
        private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);

                    var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, null), new MqttPacketSerializer());
                    ClientAccepted?.Invoke(clientAdapter);
                }
                catch (Exception exception)
                {
                    MqttNetTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at default endpoint.");

                    //excessive CPU consumed if in endless loop of socket errors
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            // required for websocket transport to work
            var transferFormatFeature = connection.Features.Get <ITransferFormatFeature>();

            if (transferFormatFeature != null)
            {
                transferFormatFeature.ActiveFormat = TransferFormat.Binary;
            }


            var serializer = new MqttPacketSerializer();

            using (var adapter = new MqttConnectionContext(serializer, connection))
            {
                var args = new MqttServerAdapterClientAcceptedEventArgs(adapter);
                ClientAccepted?.Invoke(this, args);

                await args.SessionTask;
            }
        }
        private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);

                    var sslStream = new SslStream(new NetworkStream(clientSocket));
                    await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);

                    var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer());
                    ClientAccepted?.Invoke(clientAdapter);
                }
                catch (Exception exception)
                {
                    MqttNetTrace.Error(nameof(MqttServerAdapter), exception, "Error while accepting connection at TLS endpoint.");

                    //excessive CPU consumed if in endless loop of socket errors
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemple #25
0
        private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    //todo: else branch can be used with min dependency NET46
#if NET452
                    var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
#else
                    var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);
#endif
                    var clientAdapter = _communicationAdapterFactory.CreateServerCommunicationAdapter(new MqttTcpChannel(clientSocket, null));
                    ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
                }
                catch (Exception exception)
                {
                    _logger.LogError(new EventId(), exception, "Error while accepting connection at default endpoint.");

                    //excessive CPU consumed if in endless loop of socket errors
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
                }
            }
        }
 private void FireClientAcceptedEvent(IMqttChannelAdapter adapter)
 {
     ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(adapter));
 }
 private void FireClientAcceptedEvent(IMqttCommunicationAdapter adapter)
 {
     ClientAccepted?.Invoke(adapter);
 }
 private void OnClientAccepted(object sender, MqttServerAdapterClientAcceptedEventArgs e)
 {
     ClientAccepted?.Invoke(this, e);
 }
        //! Socket's BeginAccept() callback
        //  Handles new connection and create session
        private void AcceptCallback(IAsyncResult ar)
        {
            // our session
            NetSession ses = null;

            try
            {
                // Signal the main thread to continue.
                allDone.Set();

                // Get the socket that handles the client request.
                //Socket listener = sock;
                Socket     listener = (Socket)ar.AsyncState;
                Socket     handler  = listener.EndAccept(ar);
                IPEndPoint ep       = (IPEndPoint)handler.RemoteEndPoint;

                if (CanConnect(ep))
                {
                    // setup the session
                    ses = new NetSession(handler)
                    {
                        Id = NewSessionId()
                    };

                    // bind session event handler
                    ses.Notified         += new Action <NotifyEventArgs>(NetSession_Notified);
                    ses.ConnectionClosed += new ConnectionClosed(NetSession_Closed);
                    ses.DataReceived     += new DataReceived(NetSession_DataReceived);

                    ses.BeginReceive();

                    // add session to our table
                    lock (sessions)
                    {
                        sessions.Add(ses.Id, ses);
                    }

                    // Call ClientAccepted handler
                    ClientAccepted?.Invoke(ses);
                }
                else
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }

                // start listen for connections again.
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
            }
            catch (SocketException e)
            {
                if (ses != null)
                {
                    ses.Close();
                }

                // Queue the next accept, think this should be here, stop attacks based on killing the waiting listeners
                if (sock != null)
                {
                    sock.BeginAccept(new AsyncCallback(AcceptCallback), sock);
                }
            }
            catch (Exception e)
            {
                if (ses != null)
                {
                    ses.Close();
                }

                // Queue the next accept, think this should be here, stop attacks based on killing the waiting listeners
                if (sock != null)
                {
                    sock.BeginAccept(new AsyncCallback(AcceptCallback), sock);
                }
            }
        }
Exemple #30
0
 private void OnClientAccepted(object sender, ClientAcceptedEventArgs e) => ClientAccepted?.Invoke(sender, e);