Example #1
0
        public void Start()
        {
            try
            {
                if (isRunning || socket.Connected)
                {
                    logger.Info($"client {remoteIp} connected");

                    OnClientConnected?.Invoke(this);
                    BeginReceive();
                }
                else
                {
                    if (ipResolve is null)
                    {
                        logger.Error("cannot start socket : no remote ip defined");
                        return;
                    }

                    socket.BeginConnect(ipResolve, _clientConnected, socket);
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
        }
Example #2
0
        public virtual void OnPeerConnected(NetPeer peer)
        {
            //
            Logger.Log("[S] Player connected: " + peer.EndPoint);

            OnClientConnected?.Invoke();
        }
Example #3
0
        // messages should always be processed in early update
        public override void ClientEarlyUpdate()
        {
            // note: process even if not connected because when calling
            // Disconnect, we add a Disconnected event which still needs to be
            // processed here.
            while (clientIncoming.Count > 0)
            {
                Message message = clientIncoming.Dequeue();
                switch (message.eventType)
                {
                case EventType.Connected:
                    Debug.Log("MemoryTransport Client Message: Connected");
                    // event might be null in tests if no NetworkClient is used.
                    OnClientConnected?.Invoke();
                    break;

                case EventType.Data:
                    Debug.Log($"MemoryTransport Client Message: Data: {BitConverter.ToString(message.data)}");
                    // event might be null in tests if no NetworkClient is used.
                    OnClientDataReceived?.Invoke(new ArraySegment <byte>(message.data), 0);
                    break;

                case EventType.Disconnected:
                    Debug.Log("MemoryTransport Client Message: Disconnected");
                    // event might be null in tests if no NetworkClient is used.
                    OnClientDisconnected?.Invoke();
                    break;
                }
            }
        }
        private void RegisterMirrorEvents()
        {
            // Server
            _svConnected    = (id) => OnServerConnected?.Invoke(id);
            _svDisconnected = (id) => OnServerDisconnected?.Invoke(id);
            _svDataReceived = (id, data) => OnServerDataReceived?.Invoke(id, new ArraySegment <byte>(data));
            _svError        = (id, exception) => OnServerError?.Invoke(id, exception);

            Server.OnConnected    += _svConnected;
            Server.OnDisconnected += _svDisconnected;
            Server.OnDataReceived += _svDataReceived;
            Server.OnError        += _svError;

            // Client
            _clConnected    = () => OnClientConnected?.Invoke();
            _clDisconnected = () => OnClientDisconnected?.Invoke();
            _clDataReceived = (data) => OnClientDataReceived?.Invoke(new ArraySegment <byte>(data));
            _clError        = (exception) => OnClientError?.Invoke(exception);

            Client.OnConnected    += _clConnected;
            Client.OnDisconnected += _clDisconnected;
            Client.OnDataReceived += _clDataReceived;
            Client.OnError        += _clError;

            _eventsRegistered = true;
        }
        public async Task StartServer(int maxClients = 100)
        {
            ServerCancellationTokenSource = new CancellationTokenSource();
            Listener.Start(ServerPort);
            var taskStarted = false;

            var task = Task.Run(async() =>
            {
                var numberOfAttachedClients = 0;
                ServerCancellationTokenSource.Token.ThrowIfCancellationRequested();
                taskStarted = true;
                while (true)
                {
                    if (numberOfAttachedClients < maxClients)
                    {
                        var client = await Listener.AcceptNetworkClientAsync(ServerName);
                        if (client != null)
                        {
                            numberOfAttachedClients++;
                            OnClientConnected?.Invoke(this, client.ClientName);
                            await StartSession(client);
                        }
                    }
                    await Task.Delay(1);
                }
            }, ServerCancellationTokenSource.Token);

            while (!taskStarted)
            {
                await Task.Delay(1);
            }
        }
    public override void OnClientConnect(NetworkConnection conn)
    {
        Debug.Log("Client connected");
        OnClientConnected?.Invoke(conn);

        base.OnClientConnect(conn);
    }
Example #7
0
 public override void OnClientConnect(NetworkConnection conn)
 {
     Debug.Log("on client connect");
     Debug.Log(conn.connectionId);
     base.OnClientConnect(conn);
     OnClientConnected?.Invoke();
 }
Example #8
0
        private void UDPReceiveCallback(IAsyncResult result)
        {
            IPEndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);

            byte[] data = UdpListener.EndReceive(result, ref clientEndPoint);
            UdpListener.BeginReceive(UDPReceiveCallback, null);

            if (data.Length < 4)
            {
                return;
            }

            using (Packet packet = new Packet(data)) {
                int clientId = packet.ReadInt();

                if (clientId == 0)
                {
                    return;
                }

                if (Clients[clientId].Udp.EndPoint == null)
                {
                    Clients[clientId].Udp.Connect(clientEndPoint);
                    OnClientConnected?.Invoke(this, new ClientEventArgs(Clients[clientId], Protocol.UDP));
                    return;
                }

                if (Clients[clientId].Udp.EndPoint.ToString() == clientEndPoint.ToString())
                {
                    Clients[clientId].Udp.HandleData(packet);
                }
            }
        }
Example #9
0
        /// <summary>
        ///     Gets run when a client connects
        /// </summary>
        /// <param name="ar">
        ///     Contains socket of clientconnection
        /// </param>
        private void ClientInstance(IAsyncResult ar)
        {
            // Get the socket that handles the client request
            var listener = (Socket)ar.AsyncState;

            Socket socket;

            try
            {
                if (listener == null)
                {
                    return;
                }

                socket = listener.EndAccept(ar);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Couldn't accept client connection: {0}", ex.Message);                 // DEBUG
                return;
            }
            finally
            {
                _connected?.Set();
            }

            // Create client object
            var client = new HostConnection(socket);

            // Invoke event
            Task.Run(() => OnClientConnected?.Invoke(client));
        }
Example #10
0
        private bool ProcessClientMessages()
        {
            while (MirrorClientIncomingQueue.TryDequeue(out IncomingPacket pkt))
            {
                switch (pkt.type)
                {
                case MirrorPacketType.ClientConnected:
                    if (DebugEnabled)
                    {
                        print($"Ignorance: We have connected!");
                    }
                    isClientConnected = true;
                    OnClientConnected?.Invoke();
                    break;

                case MirrorPacketType.ClientDisconnected:
                    if (DebugEnabled)
                    {
                        print($"Ignorance: We have been disconnected.");
                    }
                    isClientConnected = false;
                    OnClientDisconnected?.Invoke();
                    break;

                case MirrorPacketType.ClientGotData:
                    OnClientDataReceived?.Invoke(new ArraySegment <byte>(pkt.data));
                    break;
                }
            }
            return(true);
        }
Example #11
0
 public bool Connect(IPEndPoint endPoint)
 {
     if (!active)
     {
         try
         {
             this.client = new TcpClient();
             this.client.Connect(endPoint);
             NetworkStream networkStream = this.client.GetStream();
             this.networkConnection = new NetworkConnection(ref networkStream, (IPEndPoint)client.Client.RemoteEndPoint);
             this.networkConnection.OnSuccessfulConnection += (x, y) => OnClientConnected?.Invoke(x, y);
             this.networkConnection.OnError        += (x, y) => OnError?.Invoke(x, y);
             this.networkConnection.OnReceived     += (x, y) => OnReceived?.Invoke(x, y);
             this.networkConnection.OnDisconnected += (x, y) => OnClientDisconnected?.Invoke(x, y);
             this.active = true;
         }
         catch (Exception e)
         {
             OnError?.Invoke(networkConnection, e);
         }
         finally
         {
             if (!active)
             {
                 this.networkConnection?.Shutdown();
                 this.client?.Close();
                 this.networkConnection = null;
                 this.client            = null;
             }
         }
     }
     return(active);
 }
Example #12
0
 public async Task StartAsFirstNodeAsync(IEndPoint sourceEndPoint, IEndPoint publicEndPoint, IAsymmetricKey key, ISymmetricKey dummySymmetricKey, byte[] selfCustomData)
 {
     if (CurrentStatus != ClientStatus.NotConnected)
     {
         return;
     }
     if (selfCustomData.Length > 65000) //TODO
     {
         throw new DnmpException("Custom data length is larger than 65000 bytes");
     }
     SelfCustomData = selfCustomData;
     SelfClient     = new DnmpNode
     {
         Id         = 0,
         EndPoint   = publicEndPoint,
         CustomData = SelfCustomData
     };
     Initialize(sourceEndPoint, key, dummySymmetricKey);
     CurrentStatus = ClientStatus.Connected;
     logger.Info($"Started as first node on {sourceEndPoint} [{publicEndPoint}]");
     OnClientConnected?.Invoke(SelfClient.Id);
     OnConnected?.Invoke();
     MessageInterface.Initialize(SelfClient.Id);
     await Task.Delay(0);
 }
Example #13
0
        private void ClientAccepted(IAsyncResult ar)
        {
            //Try to accept
            try
            {
                //Open
                var clientSock = serverSock.EndAccept(ar);

                //Create client
                var client = funcConstructClient(this, clientSock);

                //Add to clients
                lock (connectedClients)
                    connectedClients.Add(client);
                OnClientConnected?.Invoke(client);

                //Listen
                client.ListenIncoming();
            }
            catch (Exception ex)
            {
                Log("ClientAccepted", "Unexpected error accepting client: " + ex.Message + ex.StackTrace, DeltaLogLevel.High);
            }

            //Listen
            serverSock.BeginAccept(ClientAccepted, null);
        }
Example #14
0
        private void ClientConnected(AuthClient client)
        {
            //Chama evento OnClientConnected
            OnClientConnected?.Invoke(client);

            Console.WriteLine($"Server: {client.Name} | Type: {client.Type} Connected");
        }
Example #15
0
 private void FireOnClientConnected(TcpClient cli)
 {
     if (cli != null)
     {
         OnClientConnected?.Invoke(this, new TcpServerStreamSource(cli));
     }
 }
Example #16
0
        private async Task ProcessClient(TcpClient client)
        {
            logger?.LogInformation("{0} connected", client.Client.RemoteEndPoint);

            TcpNetworkTransport tcpNetworkTransport = new TcpNetworkTransport(cancellationToken, client, loggerFactory);

            switch (PerformHandshake(client, tcpNetworkTransport, out string clientId))
            {
            case HandshakeResults.NewClientConnected:
                InsecureClient insecureClient = new InsecureClient(tcpNetworkTransport, loggerFactory, serializer, orderingService,
                                                                   cancellationToken, sendIdempotencyService, receiveIdempotencyService, delaySequenceGenerator, millisecondsIntervalForPacketResend,
                                                                   keepAliveTimeOut, maximumNumberOfKeepAliveMisses, keepAliveResponseTimeOut);
                clients.TryAdd(clientId, insecureClient);
                await tcpNetworkTransport.SendData(Encoding.Unicode.GetBytes(Id));

                OnClientConnected?.Invoke(insecureClient);
                break;

            case HandshakeResults.ExsistingClientReconnected:
                clients[clientId].ClientReconnected(tcpNetworkTransport);
                await tcpNetworkTransport.SendData(Encoding.Unicode.GetBytes(Id));

                break;

            case HandshakeResults.HandshakeFailed:
                tcpNetworkTransport.DropConnection();
                client.Close();
                client.Dispose();
                break;
            }
        }
Example #17
0
        //Client Accept
        private void handleConnections()
        {
            while (s_master != null)
            {
                lock (m_Locker)
                {
                    try
                    {
                        Socket client = s_master.AcceptSocket();
                        //client.NoDelay = true;
                        //client.Blocking = false;

                        if (client.Connected == false)
                        {
                            continue;
                        }
                        OnClientConnected?.Invoke(client);
                    }
                    catch (Exception s_Ex)
                    {
                        Logger.ExceptionToLog(s_Ex, "[TcpServer::handleConnections()] -> Error while starting AcceptSocket() context.");
                    }
                }
                Thread.Sleep(1);
            }
        }
Example #18
0
        private void _clientConnected(IAsyncResult ar)
        {
            logger.Info($"client {remoteIp} connected");

            OnClientConnected?.Invoke(this);

            BeginReceive();
        }
Example #19
0
 private void OnClientConnectedFromVoice(ushort handle)
 {
     Log(LogLevel.Trace, $"OnClientConnectedFromVoice({handle})");
     RunWhenClientValid(handle, client =>
     {
         InvokeProtectedEvent(() => OnClientConnected?.Invoke(client));
     });
 }
Example #20
0
        private static void OnPeerConnected(Peer peer)
        {
            ServerOutput.Line($"Connection {peer.ConnectionID} received from {peer.EndPoint}");

            Network.AddPeer(peer);

            OnClientConnected?.Invoke(peer);
        }
Example #21
0
 void OnClientStatusChanged(NetConnectionStatus inNewStatus, NetIncomingMessage inMsg)
 {
     Console.WriteLine(inMsg.SenderConnection + ": " + inNewStatus.ToString());
     if (inNewStatus == NetConnectionStatus.Connected)
     {
         OnClientConnected?.Invoke(inMsg.SenderConnection);
     }
 }
    public override void OnClientConnect(NetworkConnection conn)
    {
        NotifyPlayersOfReadyState();

        base.OnClientConnect(conn);

        OnClientConnected?.Invoke();
    }
Example #23
0
    public override void OnClientConnect(NetworkConnection conn)
    {
        // hace la logica base
        base.OnClientConnect(conn);

        // ejecuta nuestro evento
        OnClientConnected?.Invoke();
    }
Example #24
0
        private void ClientConnected(AuthClient Server)
        {
            //Chama evento OnClientConnected
            OnClientConnected?.Invoke(Server);

            WriteConsole.WriteLine($"[CLIENT_CONNECTED]: {Server.Data.Name} | Type: {Server.Data.Type}", ConsoleColor.Green);
            UpdateServer();
        }
Example #25
0
        private void ReadSocketAsync(Socket clientSocket)
        {
            var buffer        = new byte[512];
            var receivedCount = clientSocket.Receive(buffer);
            var message       = new ClientRequest(Encoding.UTF8.GetString(buffer.Take(receivedCount).ToArray()), clientSocket);

            OnClientConnected?.Invoke(this, message);
        }
        private void SocketServer_OnClientDataRecived(ClientSocket client, string msg)
        {
            OnMessageRecived?.Invoke(string.Format("SocketServer_OnClientDataRecived {0}", msg));
            JObject jObject = JObject.Parse(msg);

            PacketType packetType = (PacketType)Enum.Parse(typeof(PacketType), jObject.ToObject <Packet>().PacketType);

            if (packetType == PacketType.ClientConnected)
            {
                if (!ChatClientManager.ReadOnlyChatClients.ContainsKey(client.IPAddress))
                {
                    ChatClient chatClient = ChatClientManager.AddClient(client, jObject.ToObject <ClientConnected>());
                    OnMessageRecived?.Invoke(string.Format("Client {0} authenticized", client.IPAddress.ToString()));
                    OnClientConnected?.Invoke(chatClient);
                }
                else
                {
                    OnErrMessageRecived?.Invoke(string.Format("Client {0} trying authenticize mulitiple times!", client.IPAddress.ToString()));
                }

                return;
            }

            if (ChatClientManager.ReadOnlyChatClients.ContainsKey(client.IPAddress) == false)
            {
                OnErrMessageRecived?.Invoke(string.Format("Unauthenticized or Disposed client {0} trying send data!", client.IPAddress.ToString()));
                return;
            }

            ChatClient indexedClient = ChatClientManager.ReadOnlyChatClients[client.IPAddress];

            switch (packetType)
            {
            case PacketType.ClientDisConnect:
                if (SocketServer.ClientSockets.ContainsKey(client.IPAddress))
                {
                    indexedClient.ClientSocket.Dispose();
                    OnMessageRecived?.Invoke(string.Format("client {0} disposed", client.IPAddress.ToString()));
                }
                break;

            case PacketType.Message:
                indexedClient.OnRootMessageRecived(jObject.ToObject <Message>());
                OnMessageRecived?.Invoke(string.Format("Message recived from client {0}", client.IPAddress.ToString()));
                OnClientDataRecived?.Invoke(indexedClient, jObject);
                break;

            case PacketType.GPS:
                indexedClient.GPSdata = new GPSdata(jObject.ToObject <GPS>().GPSdata);
                OnMessageRecived?.Invoke(string.Format("GPS value recived from client {0}", client.IPAddress.ToString()));
                OnClientDataRecived?.Invoke(indexedClient, jObject);
                break;

            default:
                OnErrMessageRecived?.Invoke(string.Format("Unidentified packet {0} recived from client {1}", ((int)packetType).ToString(), client.IPAddress.ToString()));
                break;
            }
        }
Example #27
0
    private void OnClientConnectedCallbak(ulong clientId)
    {
        Debug.LogFormat("Client connected: {0} (is server: {1})", clientId, NetworkManager.Singleton.IsServer);

        if (NetworkManager.Singleton.IsServer)
        {
            OnClientConnected?.Invoke();
        }
    }
Example #28
0
        /// <summary>
        /// Creates the session after connecting
        /// </summary>
        /// <returns>Session created with listener</returns>
        private Session CreateSession()
        {
            Session session = new Session(_socket, SessionType.CLIENT_TO_SERVER);

            OnClientConnected?.Invoke(session);

            session.WaitForDataNoEncryption();
            return(session);
        }
Example #29
0
 public void ListenForConnectionsInANewThread(int port)
 {
     connectionListener.ListenForConnectionsInANewThread(port);
     connectionListener.OnClientConnected += tcpClient =>
     {
         communicator.SetupCommunicationWith(tcpClient);
         OnClientConnected?.Invoke();
     };
 }
    public override void OnConnected(NetworkConnection conn)
    {
        Debug.Log("ON CLIENT CONNECTED");
        //conn.RegisterHandler(MsgType.Highest + 1, OnMsgReceived);
        //conn.RegisterHandler(MsgType.Highest + 2, OnMsgReceived2);

        base.OnConnected(conn);
        OnClientConnected?.Invoke(conn);
    }