Ejemplo n.º 1
0
        private void Run()
        {
            try
            {
                TcpListener server = new TcpListener(IPAddress.Any, port);

                server.Start();
                ServerStarted?.Invoke();

                while (!stop)
                {
                    if (server.Pending())
                    {
                        Socket connection = server.AcceptSocket();

                        Worker w = new Worker(this, connection, "Client " + idCounter++);
                        lock (workersLock)
                        {
                            workers.Add(w);
                            UserConnected?.Invoke(w.Username);
                        }
                    }
                }

                server.Server.Close(); // Release all resources
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                ServerClosed?.Invoke();
            }
        }
Ejemplo n.º 2
0
 private void ConnectCommand(NetworkMessage message)
 {
     if (message.TryGetObject <string>(out string connectedUser))
     {
         UserConnected?.Invoke(connectedUser);
     }
 }
Ejemplo n.º 3
0
        private void NotifierOnUserConnected(object sender, NotifierEventArgs <User> notifierEventArgs)
        {
            if (notifierEventArgs?.Payload != null)
            {
                var user = notifierEventArgs.Payload;

                Friends.Add(user);

                UserConnected?.Invoke(this, notifierEventArgs);
            }
        }
Ejemplo n.º 4
0
        public void UpdateServer()
        {
            NetIncomingMessage inc = null;

            while (server != null && (inc = server.ReadMessage()) != null)
            {
                switch (inc.MessageType)
                {
                case NetIncomingMessageType.StatusChanged:
                    Console.WriteLine(inc.SenderEndPoint.ToString() + " Status: " + inc.SenderConnection.Status.ToString());
                    switch (inc.SenderConnection.Status)
                    {
                    case NetConnectionStatus.Connected:
                        if ((connections.Count >= maxConnections && maxConnections > 0) || AcceptIncomingConnections == false)
                        {
                            inc.SenderConnection.Disconnect("Server full");
                        }
                        else
                        {
                            connections.Add(inc.SenderConnection);
                            UserConnected?.Invoke(this, new ProviderUserEventArgs()
                            {
                                UserKey = inc.SenderConnection,
                            });
                        }
                        break;

                    case NetConnectionStatus.Disconnected:
                        connections.Remove(inc.SenderConnection);
                        UserDisconnected?.Invoke(this, new ProviderUserEventArgs()
                        {
                            UserKey = inc.SenderConnection,
                        });
                        break;
                    }
                    break;

                case NetIncomingMessageType.Data:
                    var bytes = inc.ReadBytes(inc.LengthBytes);
                    DataReceived?.Invoke(this, new ProviderDataEventArgs(inc.SenderConnection, true, new DataBuffer(bytes), inc.LengthBytes));
                    break;

                case NetIncomingMessageType.Error:
                case NetIncomingMessageType.ErrorMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                    Console.WriteLine(DateTime.Now.ToShortTimeString() + "Lidgren Server" + inc.ReadString());
                    break;
                }
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Trace the event that a client connected.
 /// </summary>
 /// <param name="remoteAddress">The client that connected.</param>
 internal void TraceUserConnection(IPEndPoint remoteAddress)
 {
     Task.Run(() =>
     {
         lock (ConnectedUsersSyncRoot)
             connectedUsers.Add(remoteAddress);
         try
         {
             UserConnected?.Invoke(remoteAddress);
         }
         catch { }
     });
 }
Ejemplo n.º 6
0
 private void StartAccept()
 {
     isAccepting  = true;
     acceptThread = new Thread(() =>
     {
         while (isAccepting)
         {
             var user = new GameUser(string.Empty, main.Accept());
             pool.Add(user);
             UserConnected?.Invoke(this, new GameEventArgs(user, string.Empty));
         }
     });
     acceptThread.IsBackground = true;
     acceptThread.Start();
 }
Ejemplo n.º 7
0
        private void OnConnect(IAsyncResult ar)
        {
            var conn = ar.AsyncState as Socket;

            conn.EndConnect(ar);

            if (conn.Connected)
            {
                UserConnected?.Invoke(this, new ProviderUserEventArgs()
                {
                    UserKey = conn
                });

                StateObject state = new StateObject();
                state.socket = conn;
                conn.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, OnReceive, state);
            }
        }
Ejemplo n.º 8
0
        public void TryConnectClient(DirectClientProvider client)
        {
            if (AcceptIncomingConnections)
            {
                Clients.Add(client);

                UserConnected?.Invoke(this, new ProviderUserEventArgs()
                {
                    UserKey = client,
                });

                client.AcceptConnection(this);
            }
            else
            {
                client.RejectConnection(this);
            }
        }
Ejemplo n.º 9
0
        private void OnClientConnect(IAsyncResult asyncResult)
        {
            try
            {
                Socket socket = this.serverSocket.EndAccept(asyncResult);
                var    conn   = new TcpConnection(socket);
                conn.Disconnected += this.OnClientDisconnected;
                conn.StartListen();

                connections.TryAdd(conn.Id, conn);

                UserConnected?.Invoke(conn);

                serverSocket.BeginAccept(this.OnClientConnect, null);
            }
            catch (ObjectDisposedException)
            {
                // This exception was preventing the console from closing when the
                // shutdown command was issued.
            }
        }
        public virtual void Add(IOnlineClient client)
        {
            lock (SyncObj)
            {
                var userWasAlreadyOnline = false;
                var context = client.ToClientContextOrNull();

                if (context != null)
                {
                    userWasAlreadyOnline = this.IsOnline(context);
                }

                Store.Add(client);

                ClientConnected?.Invoke(this, new OnlineClientEventArgs(client));

                if (context != null && !userWasAlreadyOnline)
                {
                    UserConnected?.Invoke(this, new OnlineUserEventArgs(context, client));
                }
            }
        }
Ejemplo n.º 11
0
        public void Connect(INetContext context)
        {
            if (IsConnected)
            {
                Disconnect();
            }

            message = new byte[1024 * 512];

            client = new TcpClient {
                NoDelay = false
            };

            client.SendBufferSize = client.ReceiveBufferSize = 1024 * 256;
            client.Connect(context.IPAddress, context.Port);

            if (client.Connected)
            {
                UserConnected?.Invoke(this, new ProviderUserEventArgs());
                IsConnected = true;
            }
        }
Ejemplo n.º 12
0
        public void Init()
        {
            if (_isInitialized)
            {
                return;
            }
            _isInitialized = true;

            _hubConnection = new HubConnection(Secrets.GoHubUrl);
            _goHub         = _hubConnection.CreateHubProxy("GoHub");

            _goHub.On(nameof(UserConnected), (UserPrefs user) => UserConnected?.Invoke(user));
            _goHub.On(nameof(UserDisconnected), (string user) => UserDisconnected?.Invoke(user));

            _goHub.On(nameof(LobbyPost), (Post post) => LobbyPost?.Invoke(post));
            _goHub.On(nameof(GamePost), (Post post) => GamePost?.Invoke(post));

            _goHub.On(nameof(GameRequested), (string name) => GameRequested?.Invoke(name));
            _goHub.On(nameof(GameRequestDeclined), (string name) => GameRequestDeclined?.Invoke(name));
            _goHub.On(nameof(GameRequestCancelled), (string name) => GameRequestCancelled?.Invoke(name));
            _goHub.On(nameof(GameRequestAccepted), (string name) => GameRequestAccepted?.Invoke(name));

            _goHub.On(nameof(GameAborted), (string name) => GameAborted?.Invoke(name));
        }
Ejemplo n.º 13
0
        public void UpdateClient()
        {
            NetIncomingMessage inc = null;

            while (client != null && (inc = client.ReadMessage()) != null)
            {
                switch (inc.MessageType)
                {
                case NetIncomingMessageType.StatusChanged:
                    switch (inc.SenderConnection.Status)
                    {
                    case NetConnectionStatus.Connected:
                        UserConnected?.Invoke(this, new ProviderUserEventArgs());
                        break;

                    case NetConnectionStatus.Disconnected:
                        UserDisconnected?.Invoke(this, new ProviderUserEventArgs());
                        break;
                    }
                    break;

                case NetIncomingMessageType.Data:
                    var bytes = inc.ReadBytes(inc.LengthBytes);
                    DataReceived?.Invoke(this, new ProviderDataEventArgs(null, true, new DataBuffer(bytes), inc.LengthBytes));
                    break;

                case NetIncomingMessageType.Error:
                case NetIncomingMessageType.ErrorMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                    Console.WriteLine(DateTime.Now.ToShortTimeString() + "Lidgren Client" + inc.ReadString());
                    break;
                }
            }
        }
Ejemplo n.º 14
0
 protected virtual void OnUserConnected(ulong userId, uint roomId)
 {
     UserConnected?.Invoke(userId, roomId);
 }
Ejemplo n.º 15
0
 public void OnUserConnected(object sender, NotifierEventArgs <User> eventArgs)
 {
     UserConnected?.Invoke(sender, eventArgs);
 }
Ejemplo n.º 16
0
        public void UpdateServer()
        {
            if (IsActive == false)
            {
                return;
            }

            //If any clients are waiting to connect
            if (clientListener != null && clientListener.Pending())
            {
                TcpClient newClient = clientListener.AcceptTcpClient();
                newClient.SendBufferSize = newClient.ReceiveBufferSize = 1024 * 256;
                newClient.NoDelay        = false;

                if (AcceptIncomingConnections)
                {
                    connected.Add(newClient);
                    clientList.Add(newClient);

                    //Delegate
                    UserConnected?.Invoke(this, new ProviderUserEventArgs()
                    {
                        UserKey = newClient,
                    });
                }
            }

            if (clientList == null)
            {
                return;
            }

            //Update each client, listening for any incoming data.
            for (int i = clientList.Count - 1; i >= 0; i--)
            {
                TcpClient tcpClient = clientList[i];

                //If the client is no longer connected, fire off a disconnection event delegate
                if (!tcpClient.Connected)
                {
                    DisconnectUser(tcpClient);
                    continue;
                }

                //Attempt to read any incoming data from this client
                int           bytesRead      = 0;
                int           totalBytesRead = 0;
                NetworkStream messageStream  = tcpClient.GetStream();
                MemoryStream  memStream      = new MemoryStream();

                if (messageStream.DataAvailable)
                {
                    var buff = new DataBuffer();
                    while (messageStream.DataAvailable)
                    {
                        bytesRead = messageStream.Read(message, 0, message.Length);
                        byte[] data = new byte[bytesRead];
                        Array.Copy(message, data, bytesRead);
                        buff.Write((byte[])data, 0, data.Length);
                        totalBytesRead += bytesRead;
                    }

                    buff.Seek(0);
                    while (buff.GetPosition() < buff.GetLength())
                    {
                        var size = buff.ReadInt16();
                        if (size == 0)
                        {
                            break;
                        }

                        byte[] d = new byte[size];
                        buff.ReadBytes(d, 0, d.Length);

                        d = Decompress(d);
                        if (d.Length == 1 && d[0] == 0)
                        {
                            DisconnectUser(tcpClient);
                            break;
                        }

                        DataBuffer msgBuffer = new DataBuffer(d);
                        msgBuffer.Seek(0);

                        //Delegate that other classes can attach to, mainly the network handler
                        DataReceived?.Invoke(this, new ProviderDataEventArgs(tcpClient, true, msgBuffer, msgBuffer.GetLength()));
                    }
                }
            }
        }
Ejemplo n.º 17
0
 void UserConnectedHandler(string _userName)
 {
     UserConnected?.Invoke(this, _userName);
 }
Ejemplo n.º 18
0
 private static void Client_ClientConnected(Client sender)
 {
     connectedClients.Add(sender);
     UserConnected?.Invoke(sender);
 }
Ejemplo n.º 19
0
        private static void Responses()
        {
            while (ResponseThreadRunning)
            {
                // listens to responses from the middle man server
                string response = GetResponse();
                if (response != "")
                {
                    string[] sections     = response.Split('|');
                    string   responseType = sections[0];
                    string   parameters   = sections[1].Replace("\r", "").Replace("\n", "");

                    Console.WriteLine(responseType + " | " + parameters);

                    switch (responseType)
                    {
                    case "CONNECTED":
                        User.Name = parameters;
                        ConnectedSuccess?.Invoke();
                        break;

                    case "PING":
                        SendMessage("PONG|");
                        break;

                    case "LOBBY_LIST":
                        string[]             lobbies   = parameters.Split(',');
                        List <LobbyListItem> lobbyList = new List <LobbyListItem>();
                        foreach (string lobby in lobbies)
                        {
                            string[] info = lobby.Split('-');
                            if (int.TryParse(info[0], out int id) && int.TryParse(info[2], out int status) && int.TryParse(info[3], out int player_count))
                            {
                                lobbyList.Add(new LobbyListItem(id, info[1], (LobbyStatus)status, player_count));
                            }
                        }
                        NewLobbyList?.Invoke(lobbyList);
                        break;

                    case "HOSTING":
                        LobbyCreated?.Invoke();
                        break;

                    case "PUNCH-HOST":
                        Console.WriteLine("HOST PUNCHING");
                        Socket connectionToC = PerformPunchThrough(sections[1].Split(':'));
                        if (connectionToC != null)
                        {
                            SendMessage("PLAYER_CONNECT_SUCCESS|");
                            UserConnected?.Invoke(connectionToC);
                        }
                        else
                        {
                            SendMessage("PLAYER_CONNECT_FAIL|");
                        }
                        break;

                    case "PUNCH-CLIENT":
                        Console.WriteLine("CLIENT PUNCHING");
                        Socket connectionToH = PerformPunchThrough(sections[1].Split(':'));
                        if (connectionToH != null)
                        {
                            JoinLobbySuccess?.Invoke(connectionToH);
                        }
                        else
                        {
                            JoinLobbyFailure.Invoke();
                        }
                        break;
                    }
                }
                else
                {
                    // AttemptReconnect();
                    break;
                }
            }
        }
 public void NotifyUserConnected()
 {
     UserConnected?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 21
0
 protected virtual void OnUserConnected(User user, Channel channel, Server server)
 {
     UserConnected?.Invoke(this, new UserConnectedEvent(user, channel, server, _client));
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Read and prosess data from stream
        /// </summary>
        private void ClientStreamReadData()
        {
            try
            {
                using (Stream stream = _server.GetStream())
                {
                    BinaryReader streamReader = new BinaryReader(stream);
                    while (true)
                    {
                        PacketType packetType = (PacketType)streamReader.ReadInt32();

                        switch (packetType)
                        {
                        case PacketType.Negotiation:
                            NegotiationPacket negotiationPacket = new NegotiationPacket(stream);
                            negotiationPacket.Receive();
                            Login = negotiationPacket.Login;
                            _loginEvents[0].Set();
                            _registerEvents[0].Set();
                            lock (_rooms)
                            {
                                Room mainRoom = new Room(Room.MainRoomId, Room.MainRoomName, new HashSet <string>());
                                _rooms.Add(Room.MainRoomId, mainRoom);
                            }
                            _context.Post(p => NegotiationCompleted?.Invoke(this, EventArgs.Empty), null);
                            break;

                        case PacketType.SimpleMessage:
                            SimpleMessagePacket simpleMessagePacket = new SimpleMessagePacket(stream);
                            simpleMessagePacket.Receive();
                            OnSimpleMessageReceived(simpleMessagePacket);
                            break;

                        case PacketType.Error:
                            ErrorPacket errorPacket = new ErrorPacket(stream);
                            errorPacket.Receive();
                            _context.Post(p => ErrorOccurred?.Invoke(this, new ErrorOccurredEventHandlerArgs(errorPacket.ErrorMessage, errorPacket.ErrorType)), null);
                            break;

                        case PacketType.UserConnect:
                            UserConnectPacket userConnectPacket = new UserConnectPacket(stream);
                            userConnectPacket.Receive();
                            lock (_users)
                            {
                                _users[userConnectPacket.UserLogin] = userConnectPacket.UserInfo;
                            }
                            _context.Post(p => UserConnected?.Invoke(this, new UserConnectedEventHandlerArgs(userConnectPacket.UserLogin, userConnectPacket.UserInfo)), null);
                            break;

                        case PacketType.UserDisconnect:
                            UserDisconnectPacket userDisconnectPacket = new UserDisconnectPacket(stream);
                            userDisconnectPacket.Receive();
                            lock (_users)
                            {
                                _users.Remove(userDisconnectPacket.UserLogin);
                            }
                            _context.Post(p => UserDisconnected?.Invoke(this, new UserDisconnectedEventHandlerArgs(userDisconnectPacket.UserLogin)), null);
                            break;

                        case PacketType.CreateNewRoom:
                            CreateNewRoomPacket createNewRoomPacket = new CreateNewRoomPacket(stream);
                            createNewRoomPacket.Receive();
                            lock (_rooms)
                            {
                                _rooms.Add(createNewRoomPacket.Room.Id, createNewRoomPacket.Room);
                            }
                            _context.Post(p => NewRoomCreated?.Invoke(this, new NewRoomCreatedEventHandlerArgs(createNewRoomPacket.Room)), null);
                            break;

                        case PacketType.AddUserToRoom:
                            AddUsersToRoomPacket addUsersToRoomPacket = new AddUsersToRoomPacket(stream);
                            addUsersToRoomPacket.Receive();
                            lock (_rooms)
                            {
                                foreach (string user in addUsersToRoomPacket.Users)
                                {
                                    _rooms[addUsersToRoomPacket.RoomId].Members.Add(user);
                                }
                            }
                            _context.Post(p => RoomsUpdated?.Invoke(this, new RoomsUpdatedEventHandlerArgs()), null);
                            break;

                        case PacketType.RemoveUserFromRoom:
                            RemoveUserFromRoomPacket removeUserFromRoomPacket = new RemoveUserFromRoomPacket(stream);
                            removeUserFromRoomPacket.Receive();
                            lock (_rooms)
                            {
                                Room room;
                                if (_rooms.TryGetValue(removeUserFromRoomPacket.RoomId, out room))
                                {
                                    room.Members.Remove(removeUserFromRoomPacket.User);
                                }
                            }
                            _context.Post(p => RoomsUpdated?.Invoke(this, new RoomsUpdatedEventHandlerArgs()), null);
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            {
                _server.Close();
                _server.Client.Dispose();
            }
        }
Ejemplo n.º 23
0
 public void AcceptConnection(DirectServerProvider Server)
 {
     IsConnected  = true;
     ActiveServer = Server;
     UserConnected?.Invoke(this, new ProviderUserEventArgs());
 }