예제 #1
0
        void OnSocketReceived(object sender, SocketAsyncEventArgs e)
        {
            Socket socket = null;

            try {
                // Capture the socket (if any) and prepare the args for reuse
                // by ensuring AcceptSocket is null.
                socket         = e.AcceptSocket;
                e.AcceptSocket = null;

                if (e.SocketError != SocketError.Success)
                {
                    throw new SocketException((int)e.SocketError);
                }

                var connection = new SocketPeerConnection(socket, true);
                ConnectionReceived?.Invoke(this, new PeerConnectionEventArgs(connection, null));
            } catch {
                socket?.Close();
            }

            try {
                if (!((Socket)sender).AcceptAsync(e))
                {
                    OnSocketReceived(sender, e);
                }
            } catch {
                return;
            }
        }
예제 #2
0
 private void OnConnectionReceived(object sender, ListenerConnectEventArgs e)
 {
     if (ConnectionReceived != null)
     {
         ConnectionReceived.Invoke(sender, e);
     }
 }
예제 #3
0
 public void HandleConnectionReceived(object sender, ConnectionReceivedEventArgs e)
 {
     if (!String.IsNullOrEmpty(e.Login))
     {
         ConnectionReceived?.Invoke(this, e);
     }
 }
예제 #4
0
        private void DoStartAdvertising()
        {
            Task.Run(() =>
            {
                _listenerSocket = BluetoothSockets.CreateRfcommSocket();
                _listenerSocket.Bind(new BluetoothEndPoint(0, _serviceUuid));

                try
                {
                    _listenerSocket.Listen(1);

                    // TODO: Publish SDP record

                    while (_listenerSocket != null)
                    {
                        var socket = _listenerSocket.Accept();
                        ConnectionReceived?.Invoke(this, new RfcommConnectionReceivedEventArgs(new System.Net.Sockets.NetworkStream(socket)));
                    }
                }
                catch
                {
                    //TODO: only trap thread cancellation here
                }
            });
        }
예제 #5
0
 private void _Accept(IAsyncResult iar)
 {
     if (_Socket == null)
     {
         return;
     }
     System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)iar.AsyncState;
     try
     {
         Clients.Add(client.EndAccept(iar));
         StateObject state = new StateObject();
         state.workSocket = Clients[Clients.Count - 1];
         ConnectionReceived?.Invoke(Clients[Clients.Count - 1]);
         Clients[Clients.Count - 1].BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(_OnReceive), state);
         _Socket.BeginAccept(new AsyncCallback(_Accept), client);
     }
     catch (Exception ex)
     {
         if (ex is ObjectDisposedException)
         {
             return;
         }
         //C_Error.WriteErrorLog("DamperData", ex);
         throw;
     }
 }
 private void OnConnectionReceived(object sender, ConnectionReceivedEventArgs e)
 {
     if (!String.IsNullOrEmpty(e.Username))
     {
         ConnectionReceived?.Invoke(this, e);
     }
 }
예제 #7
0
 internal void RemoveConnection(Guid connectionId)
 {
     if (_connections.TryRemove(connectionId, out WsConnection connection) && !string.IsNullOrEmpty(connection.Username))
     {
         ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(connection.Username, false, DateTime.Now));
         ConnectionReceived?.Invoke(this, new ConnectionReceivedEventArgs(connection.Username, false, DateTime.Now));
     }
 }
예제 #8
0
 public void Add(IConnectionListener listener)
 {
     if (!_listeners.ContainsKey(listener))
     {
         _listeners.Add(listener,
                        listener.ConnectionReceived.Subscribe(conn => ConnectionReceived?.Invoke(listener, conn)));
     }
 }
예제 #9
0
        internal void OnMessage(Guid clientId, MessageContainer container)
        {
            if (!_connections.TryGetValue(clientId, out WsConnection connection))
            {
                return;
            }

            switch (container.Identifier)
            {
            case nameof(ConnectionRequest):
                var connectionRequest  = ((JObject)container.Payload).ToObject(typeof(ConnectionRequest)) as ConnectionRequest;
                var connectionResponse = new ConnectionResponse
                {
                    Result    = ResultCode.Ok,
                    IsSuccess = true,
                };
                if (_connections.Values.Any(c => c.Username == connectionRequest.Username))
                {
                    string reason = $"User '{connectionRequest.Username}' is already logged in.";
                    connectionResponse.Result    = ResultCode.Failure;
                    connectionResponse.IsSuccess = false;
                    connectionResponse.Reason    = reason;
                    connection.Send(connectionResponse.GetContainer());
                    ErrorReceived?.Invoke(this, new ErrorReceivedEventArgs(reason, DateTime.Now));
                }
                else
                {
                    connection.Username            = connectionRequest.Username;
                    connectionResponse.ActiveUsers = _connections.Where(c => c.Value.Username != null).Select(u => u.Value.Username).ToList();
                    connection.Send(connectionResponse.GetContainer());
                    ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(connection.Username, true, DateTime.Now));
                    ConnectionReceived?.Invoke(this, new ConnectionReceivedEventArgs(connection.Username, true, DateTime.Now));
                }
                break;

            case nameof(MessageRequest):
                var messageRequest = ((JObject)container.Payload).ToObject(typeof(MessageRequest)) as MessageRequest;
                MessageReceived?.Invoke(this, new MessageReceivedEventArgs(connection.Username, messageRequest.Target, messageRequest.Message, messageRequest.Groupname, DateTime.Now));
                break;

            case nameof(FiltrationRequest):
                var filtrationRequest = ((JObject)container.Payload).ToObject(typeof(FiltrationRequest)) as FiltrationRequest;
                FiltrationReceived?.Invoke(this, new FiltrationReceivedEventArgs(connection.Username, filtrationRequest.FirstDate, filtrationRequest.SecondDate, filtrationRequest.EventType));
                break;

            case nameof(CreateGroupRequest):
                var createGroupRequest = ((JObject)container.Payload).ToObject(typeof(CreateGroupRequest)) as CreateGroupRequest;
                createGroupRequest.UserList.Add(connection.Username);
                GroupCreated?.Invoke(this, new GroupCreatedEventArgs(createGroupRequest.Groupname, createGroupRequest.UserList));
                break;

            case nameof(LeaveGroupRequest):
                var leaveGroupRequest = ((JObject)container.Payload).ToObject(typeof(LeaveGroupRequest)) as LeaveGroupRequest;
                GroupLeaved?.Invoke(this, new GroupLeavedEventArgs(connection.Username, leaveGroupRequest.Groupname));
                break;
            }
        }
예제 #10
0
        protected virtual void BeginOnConnectionReceived(MessageHost host)
        {
            if (ConnectionReceived == null)
            {
                return;
            }

            var args = new TcpConnectionReceivedEventArgs(host);

            ConnectionReceived?.BeginInvoke(this, args, EndOnConnectionReceived, args);
        }
예제 #11
0
        public async void Listen()
        {
#if NETFX_CORE
            listener = new StreamSocketListener();
            listener.ConnectionReceived += NewConnection;
            listener.Control.KeepAlive   = false;

            try
            {
                await listener.BindServiceNameAsync(Port.ToString());
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                UDebug.LogException(exception);
            }
#else
            TcpListener server = null;
            try
            {
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                server = new TcpListener(localAddr, Port);

                // start listening for client requests.
                server.Start();

                // enter the listening loop
                while (true)
                {
                    // perform a blocking call to accept requests.
                    using (TcpClient tcpClient = server.AcceptTcpClient())
                    {
                        USocketClient client = new USocketClient(tcpClient);
                        ConnectionReceived?.Invoke(this, client);
                    }
                }
            }
            catch (Exception e)
            {
                UDebug.LogException(e);
            }
            finally
            {
                // stop listening for new clients
                server.Stop();
            }
#endif
        }
예제 #12
0
        /// <summary>
        /// Accepts incoming connections on supplied port
        /// </summary>
        /// <param name="result"></param>
        private void AcceptSocketConnection(IAsyncResult result)
        {
            //We received a connection, parse supplied state object to CSockState
            CSockState cSockState = result.AsyncState as CSockState;

            //Create a buffer for received data in the stateobject
            cSockState.CBuffer = new byte[1024];
            //End the acceptCall, and store created socket connection in our stateobject
            cSockState.Socket = _socket.EndAccept(result);

            ConnectionReceived.Invoke(cSockState);
            //Start listening for data on the established socket connection
            cSockState.Socket.BeginReceive(cSockState.CBuffer, 0, cSockState.CBuffer.Length, SocketFlags.None, ReceiveData, cSockState);

            //Start listening for new connections
            _socket.BeginAccept(AcceptSocketConnection, new CSockState());
        }
예제 #13
0
#pragma warning disable 4014
        private void WaitForConnections(CancellationToken cancelToken)
        {
            Task.Factory.StartNew(async() =>
            {
                while (!cancelToken.IsCancellationRequested)
                {
                    var nativeClient  = await _backingTcpListener.AcceptTcpClientAsync();
                    var wrappedClient = new TcpSocketClient(nativeClient, _bufferSize);

                    var eventArgs = new TcpSocketListenerConnectEventArgs(wrappedClient);
                    ConnectionReceived?.Invoke(this, eventArgs);
                }
            },
                                  cancelToken,
                                  TaskCreationOptions.LongRunning,
                                  TaskScheduler.Default);
        }
예제 #14
0
 private void DoStartAdvertising()
 {
     Task.Run(async() =>
     {
         try
         {
             while (_socket != null)
             {
                 var socket = await _socket.AcceptAsync();
                 ConnectionReceived?.Invoke(this, new RfcommConnectionReceivedEventArgs(new NetworkStream(socket)));
             }
         }
         catch
         {
             //TODO: only trap thread cancellation here
         }
     });
 }
예제 #15
0
        void OnSocketReceived(object sender, SocketAsyncEventArgs e)
        {
            Socket socket = null;

            try {
                // Capture the socket (if any) and prepare the args for reuse
                // by ensuring AcceptSocket is null.
                socket         = e.AcceptSocket;
                e.AcceptSocket = null;

                if (e.SocketError != SocketError.Success)
                {
                    throw new SocketException((int)e.SocketError);
                }

                IConnection connection;
                if (socket.AddressFamily == AddressFamily.InterNetwork)
                {
                    connection = new IPV4Connection(socket, true);
                }
                else
                {
                    connection = new IPV6Connection(socket, true);
                }

                var peer = new Peer("", connection.Uri, EncryptionTypes.All);
                ConnectionReceived?.Invoke(this, new NewConnectionEventArgs(peer, connection, null));
            } catch {
                socket?.Close();
            }

            try {
                if (!((Socket)sender).AcceptAsync(e))
                {
                    OnSocketReceived(sender, e);
                }
            } catch {
                return;
            }
        }
예제 #16
0
        void OnSocketReceived(object sender, SocketAsyncEventArgs e)
        {
            Socket socket = null;

            try {
                if (e.SocketError != SocketError.Success)
                {
                    throw new SocketException((int)e.SocketError);
                }
                socket = e.AcceptSocket;
                // This is a crazy quirk of the API. We need to null this
                // out if we re-use the args.
                e.AcceptSocket = null;

                IConnection connection;
                if (socket.AddressFamily == AddressFamily.InterNetwork)
                {
                    connection = new IPV4Connection(socket, true);
                }
                else
                {
                    connection = new IPV6Connection(socket, true);
                }

                var peer = new Peer("", connection.Uri, EncryptionTypes.All);
                ConnectionReceived?.Invoke(this, new NewConnectionEventArgs(peer, connection, null));
            } catch {
                socket?.Close();
            }

            try {
                if (!((Socket)sender).AcceptAsync(e))
                {
                    OnSocketReceived(sender, e);
                }
            } catch {
                return;
            }
        }
예제 #17
0
 public void DispatchConnectionReceivedEvent()
 {
     ConnectionReceived?.Invoke(null, null);
 }
예제 #18
0
        private void AcceptedHandlerInternal(INetworkTunnel tunnel)
        {
            var session = _sessionFactory.Invoke(tunnel);

            ConnectionReceived?.Invoke(session);
        }
예제 #19
0
 protected virtual void RaiseConnectionReceived(Peer peer, IConnection connection, TorrentManager manager)
 {
     ConnectionReceived?.Invoke(this, new NewConnectionEventArgs(peer, connection, manager));
 }
예제 #20
0
        private void NewConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            USocketClient client = new USocketClient(args.Socket);

            ConnectionReceived?.Invoke(this, client);
        }
예제 #21
0
        public void Add(TorrentManager manager, IConnection connection)
        {
            var p = new Peer("", new Uri("ipv4://12.123.123.1:2342"), EncryptionTypes.All);

            ConnectionReceived?.Invoke(this, new NewConnectionEventArgs(p, connection, manager));
        }
 public void MockConnectedPeer(PeerConnection connection)
 {
     ConnectionReceived?.Invoke(connection);
 }
예제 #23
0
 internal void HandleConnectionReceived(object sender, ConnectionEventArgs args)
 {
     WrappedEventHandler(() => ConnectionReceived?.Invoke(sender, args), "ConnectionReceived", sender);
 }
예제 #24
0
 public void Add(TorrentManager manager, IPeerConnection connection)
 {
     ConnectionReceived?.Invoke(this, new PeerConnectionEventArgs(connection, manager.InfoHash));
 }
        private void ServiceProvier_OnConnectionReceived(object sender, IRfcommConnection e)
        {
            RfcommRXConnection rxConnection = new RfcommRXConnection(e, ConnectionGroup);

            ConnectionReceived?.Invoke(this, rxConnection);
        }
예제 #26
0
        private void OnMessage(object sender, MessageEventArgs e)
        {
            if (!e.IsText)
            {
                return;
            }

            var container = JsonConvert.DeserializeObject <MessageContainer>(e.Data);

            switch (container.Identifier)
            {
            case nameof(ConnectionResponse):
                var connectionResponse = ((JObject)container.Payload).ToObject(typeof(ConnectionResponse)) as ConnectionResponse;
                if (connectionResponse.Result == ResultCodes.Failure)
                {
                    Login = string.Empty;
                    string source = string.Empty;
                    ErrorReceived?.Invoke(this, new ErrorReceivedEventArgs(connectionResponse.Reason, connectionResponse.Date));
                }
                if (!String.IsNullOrEmpty(Login))
                {
                    ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(Login, DateTime.Now, true, connectionResponse.OnlineClients));
                }
                break;

            case nameof(ConnectionBroadcast):
                var connectionBroadcast = ((JObject)container.Payload).ToObject(typeof(ConnectionBroadcast)) as ConnectionBroadcast;
                if (connectionBroadcast.Login != Login)
                {
                    ConnectionReceived?.Invoke(this, new ConnectionReceivedEventArgs(connectionBroadcast.Login, connectionBroadcast.IsConnected, connectionBroadcast.Date));
                }
                break;

            case nameof(MessageBroadcast):
                var messageBroadcast = ((JObject)container.Payload).ToObject(typeof(MessageBroadcast)) as MessageBroadcast;
                MessageReceived?.Invoke(this, new MessageReceivedEventArgs(messageBroadcast.Source, messageBroadcast.Target, messageBroadcast.Message, messageBroadcast.Date,
                                                                           messageBroadcast.GroupName));
                break;

            case nameof(ClientsListResponse):
                var clientsListResponse = ((JObject)container.Payload).ToObject(typeof(ClientsListResponse)) as ClientsListResponse;
                ClientsListReceived?.Invoke(this, new ClientsListReceivedEventArgs(clientsListResponse.Clients));
                break;

            case nameof(ChatHistoryResponse):
                var chatHistoryResponse = ((JObject)container.Payload).ToObject(typeof(ChatHistoryResponse)) as ChatHistoryResponse;
                ChatHistoryReceived?.Invoke(this, new ChatHistoryReceivedEventArgs(chatHistoryResponse.ClientMessages));
                break;

            case nameof(FilterResponse):
                var filterResponse = ((JObject)container.Payload).ToObject(typeof(FilterResponse)) as FilterResponse;
                FilteredMessagesReceived?.Invoke(this, new FilteredMessagesReceivedEventArgs(filterResponse.FilteredMessages));
                break;

            case nameof(GroupsListResponse):
                var groupsListResponse = ((JObject)container.Payload).ToObject(typeof(GroupsListResponse)) as GroupsListResponse;
                GroupsReceived?.Invoke(this, new GroupsReceivedEventArgs(groupsListResponse.Groups));
                break;

            case nameof(GroupBroadcast):
                var groupBroadcast = ((JObject)container.Payload).ToObject(typeof(GroupBroadcast)) as GroupBroadcast;
                GroupsReceived?.Invoke(this, new GroupsReceivedEventArgs(groupBroadcast.Group));
                break;
            }
        }
예제 #27
0
        private void OnMessage(object sender, MessageEventArgs e)
        {
            if (!e.IsText)
            {
                return;
            }

            var container = JsonConvert.DeserializeObject <MessageContainer>(e.Data);

            switch (container.Identifier)
            {
            case nameof(ConnectionResponse):
                var connectionResponse = ((JObject)container.Payload).ToObject(typeof(ConnectionResponse)) as ConnectionResponse;
                if (connectionResponse.Result == ResultCode.Failure)
                {
                    Username = string.Empty;
                    string source = string.Empty;
                    ErrorReceived?.Invoke(this, new ErrorReceivedEventArgs(connectionResponse.Reason, connectionResponse.Date));
                }
                if (!String.IsNullOrEmpty(Username))
                {
                    ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(Username, true, DateTime.Now, connectionResponse.ActiveUsers));
                }
                break;

            case nameof(ConnectionBroadcast):
                var connectionBroadcast = ((JObject)container.Payload).ToObject(typeof(ConnectionBroadcast)) as ConnectionBroadcast;
                if (connectionBroadcast.Username != Username)
                {
                    ConnectionReceived?.Invoke(this, new ConnectionReceivedEventArgs(connectionBroadcast.Username, connectionBroadcast.IsConnected, connectionBroadcast.Date));
                }
                break;

            case nameof(MessageBroadcast):
                var messageBroadcast = ((JObject)container.Payload).ToObject(typeof(MessageBroadcast)) as MessageBroadcast;
                MessageReceived?.Invoke(this, new MessageReceivedEventArgs(messageBroadcast.Source, messageBroadcast.Target, messageBroadcast.Message, messageBroadcast.Groupname, messageBroadcast.Date));
                break;

            case nameof(UserListResponse):
                var userListResponse = ((JObject)container.Payload).ToObject(typeof(UserListResponse)) as UserListResponse;
                UsersReceived?.Invoke(this, new UsersReceivedEventArgs(userListResponse.UserList));
                break;

            case nameof(MessageHistoryResponse):
                var messageHistoryResponse = ((JObject)container.Payload).ToObject(typeof(MessageHistoryResponse)) as MessageHistoryResponse;
                MessageHistoryReceived?.Invoke(this, new MessageHistoryReceivedEventArgs(messageHistoryResponse.GroupMessages));
                break;

            case nameof(FiltrationResponse):
                var filterResponse = ((JObject)container.Payload).ToObject(typeof(FiltrationResponse)) as FiltrationResponse;
                FilteredLogsReceived?.Invoke(this, new FilteredLogsReceivedEventArgs(filterResponse.FilteredLogs));
                break;

            case nameof(GroupListResponse):
                var groupsListResponse = ((JObject)container.Payload).ToObject(typeof(GroupListResponse)) as GroupListResponse;
                GroupsReceived?.Invoke(this, new GroupsReceivedEventArgs(groupsListResponse.Groups));
                break;

            case nameof(GroupBroadcast):
                var groupBroadcast = ((JObject)container.Payload).ToObject(typeof(GroupBroadcast)) as GroupBroadcast;
                GroupsReceived?.Invoke(this, new GroupsReceivedEventArgs(groupBroadcast.Groupname));
                break;
            }
        }
예제 #28
0
 private void _listener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
 {
     ConnectionReceived?.Invoke(this, new RfcommConnectionReceivedEventArgs(new NetworkStream(args.Socket)));
 }
예제 #29
0
        /// <summary>
        /// Process the receive of a connection.
        /// </summary>
        /// <param name="acceptEventArg">The parameter containing the connection information.</param>
        private void ProcessAccept(SocketAsyncEventArgs acceptEventArg)
        {
            SocketClient client = new SocketClient(acceptEventArg.AcceptSocket);

            ConnectionReceived.Invoke(client);
        }