public void AddClientConnection(NetworkConnection clientConnection)
        {
            if (clientConnection.ClientSession == null)
            {
                throw new ConnectionException("Connection does not have an ID!");
            }

            int sessionID = clientConnection.ClientSession.SessionID;

            if (ClientConnections[sessionID] != null)
            {
                throw new ConnectionException("Connection with this session ID is already in the network!");
            }

            // Can we raise a On Client Lost Event when a dead Connection get's added here ? Important after adding to the event other toctu race condition.
            clientConnection.SetUDPConnection(UdpConnection);
            clientConnection.ClientSession.SessionID = sessionID;

            if (!ClientConnections.TryAdd(sessionID, clientConnection))
            {
                throw new ConnectionException("Adding the connection failed!");
            }

            clientConnection.ConnectionDiedEvent += ErrorHandling.ConnectionDiedHandler;
        }
Example #2
0
 public override async Task SendAsync(string message)
 {
     foreach (WebSocketConnection client in ClientConnections.ToList())
     {
         await client.SendAsync(message);
     }
 }
Example #3
0
        /// <summary>
        /// Listens for new clients.
        /// </summary>
        /// <param name="obj">not used</param>
        private void listen(object obj)
        {
            eventLogger.WriteEntry("stating listen");
            TcpListener server = null;

            try
            {
                eventLogger.WriteEntry("Starting service");

                IPAddress localAddr = IPAddress.Parse(GetLocalIPAddress());

                Int32 port = 53512;
                server = new TcpListener(localAddr, port);

                eventLogger.WriteEntry("after tcplistener");

                server.Start();
                Byte[] bytes = new Byte[256];
                while (true)
                {
                    eventLogger.WriteEntry("Waiting for connection");
                    Console.Write("Waiting for a connection... ");
                    eventLogger.WriteEntry(GetLocalIPAddress());
                    Console.Write(GetLocalIPAddress());//gets this computers ip address
                    TcpClient client = server.AcceptTcpClient();
                    //Create new connection for the client that just connected
                    ClientConnections newConnection = new ClientConnections();
                    newConnection.results  = new List <Result>();
                    newConnection.cSocket  = client;
                    newConnection.score    = 0;
                    newConnection.question = -1;
                    //Create a thread the will run on loop sending this clients Connection to it
                    newConnection.rTimer = new MyTimer(0, readSocket, newConnection);
                    //Add connection to running connections list
                    connections.Add(newConnection);
                    eventLogger.WriteEntry("connection made");
                    Console.WriteLine("Connected!");
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                server.Stop();
            }


            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
Example #4
0
        /// <summary>
        /// Kills ship of client that disconnects and removes client from world
        /// </summary>
        /// <param name="ss"></param>
        public static void DisconnectClientHandler(Networking.SocketState ss, string message)
        {
            Console.WriteLine(message);
            Ship ship = TheWorld.GetShipAtId(ss.ID);

            ship.SetHp(0);
            SendWorld(); // make sure to send the world so that the client knows to terminate the ship.
            lock (TheWorld)
            {
                // remove ship and client connection associated with that ship.
                TheWorld.RemoveShipAll(ss.ID);
                ClientConnections.Remove(ss.ID);
            }
        }
Example #5
0
            public override async Task RunServerLoop()
            {
                if (ServerStarted)
                {
                    return;
                }
                ServerStarted = true;
                Task cancelTask = Task.Run(() => WaitHandle.WaitAny(new[] { TokenSource.Token.WaitHandle }));

                using (HttpListener listener = new HttpListener())
                {
                    listener.Prefixes.Add(Uri.ToString());
                    listener.Start();
                    while (!TokenSource.IsCancellationRequested)
                    {
                        Task <HttpListenerContext> listenerContextTask = listener.GetContextAsync();
                        int index = Task.WaitAny(cancelTask, listenerContextTask);
                        if (index == 0)
                        {
                            break;
                        }

                        HttpListenerContext listenerContext = listenerContextTask.Result;
                        if (!listenerContext.Request.IsWebSocketRequest)
                        {
                            listenerContext.Response.StatusCode = 400;
                            listenerContext.Response.Close();
                        }
                        else
                        {
                            HttpListenerWebSocketContext webSocketContext = await listenerContext.AcceptWebSocketAsync(null);

                            WebSocketConnection ws = new ClientConnection(webSocketContext.WebSocket,
                                                                          listenerContext.Request.RemoteEndPoint?.ToString());
                            ClientConnections.Add(ws);
                            ws.OnMessage += (e, a) => InvokeOnMessage(a);
                            ws.OnError   += (e, a) => InvokeOnError(a);
                            ws.OnClose   += (e, a) => {
                                InvokeOnClose(a);
                                ClientConnections.Remove(a.Connection);
                            };
                            InvokeOnClientConnected(new OnClientConnectedEventArgs(ws));
                        }
                    }
                }

                cancelTask.Wait();
                ServerStopEvent.Set();
            }
Example #6
0
 public override Task DisconnectAsync()
 {
     if (!ServerStarted || ServerStopEvent.WaitOne(0))
     {
         return(Task.CompletedTask);
     }
     TokenSource.Cancel();
     ServerStopEvent.WaitOne();
     foreach (WebSocketConnection conn in ClientConnections)
     {
         Task.Run(conn.DisconnectAsync);
     }
     ClientConnections.Clear();
     return(Task.CompletedTask);
 }
Example #7
0
        /// <summary>
        /// Receives the name of the client after it's connection.
        /// </summary>
        /// <param name="ss"></param>
        private static void ReceiveName(Networking.SocketState ss)
        {
            ss._call = ReceiveCommand;
            string totalData = ss.sb.ToString();

            string[] name   = totalData.Split('\n');
            Client   client = new Client(ss.ID, name[0], ss);

            // on a successful connection, add a client
            lock (TheWorld)
            {
                ClientConnections.Add(client.ID, client);
            }
            // send useful information back to client
            string startupInfo = ss.ID + "\n" + gameSettings["UniverseSize"] + "\n";

            InsertShip(ss.ID, name[0], 0);
            Networking.NetworkController.Send(startupInfo, ss);
            Networking.NetworkController.GetData(ss);
        }
        /// <summary>
        /// Listens for new clients.
        /// </summary>
        /// <param name="obj">not used</param>
        private void listen(object obj)
        {
            eventLogger.WriteEntry("stating listen");
            TcpListener server = null;
            try
            {
                eventLogger.WriteEntry("Starting service");

                IPAddress localAddr = IPAddress.Parse(GetLocalIPAddress());

                Int32 port = 53512;
                server = new TcpListener(localAddr, port);

                eventLogger.WriteEntry("after tcplistener");

                server.Start();
                Byte[] bytes = new Byte[256];
                while (true)
                {

                    eventLogger.WriteEntry("Waiting for connection");
                    Console.Write("Waiting for a connection... ");
                    eventLogger.WriteEntry(GetLocalIPAddress());
                    Console.Write(GetLocalIPAddress());//gets this computers ip address
                    TcpClient client = server.AcceptTcpClient();
                    //Create new connection for the client that just connected
                    ClientConnections newConnection = new ClientConnections();
                    newConnection.results = new List<Result>();
                    newConnection.cSocket = client;
                    newConnection.score = 0;
                    newConnection.question = -1;
                    //Create a thread the will run on loop sending this clients Connection to it
                    newConnection.rTimer = new MyTimer(0, readSocket, newConnection);
                    //Add connection to running connections list
                    connections.Add(newConnection);
                    eventLogger.WriteEntry("connection made");
                    Console.WriteLine("Connected!");
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                server.Stop();
            }

            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
 public void RemoveClientConnection(string connectionId)
 {
     ClientConnections.TryRemove(connectionId, out _);
 }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var unitOfWork = new UnitOfWorkFactory().Create())
            {
                string requestIPAddress = GetIpAddress();

                var auditLog = new AuditActivityLog()
                {
                    SenderUserID     = context.UserName,
                    SenderRequestURL = HttpContext.Current.Request.Url.OriginalString,
                    SenderIP         = requestIPAddress,
                    AuditDateTime    = DateTime.Now
                };
                var auditId = unitOfWork.AuditRepository.CreateAuditActivityLog(auditLog);
                unitOfWork.Commit();

                try
                {
                    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                    var clientUser = unitOfWork.UserRepository.GetUserByName(x => x, context.UserName,
                                                                             new List <Expression <Func <ClientUser, object> > > {
                        x => x.Client,
                        x => x.UserIPAddresses
                    });
                    if (clientUser == null || !(await unitOfWork.UserRepository.IsPasswordValidAsync(clientUser, context.Password)))
                    {
                        throw new AuthenticationException("The user name or password is incorrect.");
                    }

                    auditLog.LoginUser    = clientUser;
                    auditLog.InsightEmail = clientUser.Email;

                    if (!clientUser.Active)
                    {
                        throw new AuthenticationException("The user account is disabled.");
                    }
                    if (clientUser.Client == null)
                    {
                        throw new AuthenticationException("The user account doesn't have a client associated with it.");
                    }

                    DateTime nowDateTime = DateTime.UtcNow;

                    //Check whitelisting of IP addresses
                    if (clientUser.Client.WhitelistIPs)
                    {
                        List <ClientIPAddresses> userIPWhiteList = clientUser.UserIPAddresses == null ? null : clientUser.UserIPAddresses.Where(x => (x.IPAddress4 == requestIPAddress)).ToList();
                        if (userIPWhiteList == null || userIPWhiteList.Count() == 0)
                        {
                            throw new AuthenticationException("Connection denied.");
                        }
                    }

                    //Check number of open tokens limit
                    int openTokensLimit = clientUser.Client.OpenTokensLimit;
                    if (openTokensLimit == 0 && !Int32.TryParse(ConfigurationManager.AppSettings["opentokenslimit"], out openTokensLimit))
                    {
                        openTokensLimit = 0;
                    }

                    if (openTokensLimit > 0)
                    {
                        List <ClientConnections> openConnections = unitOfWork.AuditRepository.GetConnectionsByClient(x => x, clientUser.Client.id)
                                                                   .Where(x => nowDateTime >= x.TokenStartDateTimeUTC && nowDateTime <= x.TokenEndDateTimeUTC).ToList();
                        if (openConnections != null && openConnections.Count() > openTokensLimit)
                        {
                            throw new AuthenticationException("Total number of open connection per client exceeds the limit.");
                        }
                    }

                    //Set timeouts
                    int tokenTimespanSec = clientUser.Client.TokenTimeOut;
                    if (tokenTimespanSec == 0 && !Int32.TryParse(ConfigurationManager.AppSettings["timeoutseconds"], out tokenTimespanSec))
                    {
                        tokenTimespanSec = 900;
                    }

                    DateTime tokenExpiration = nowDateTime.AddSeconds(tokenTimespanSec);

                    auditLog.TokenStartDateTimeUTC = nowDateTime;
                    auditLog.TokenEndDateTimeUTC   = tokenExpiration;
                    unitOfWork.Commit();

                    //record new connection
                    var newConnection = new ClientConnections()
                    {
                        LoginUser = clientUser,
                        ConnectionClientAccount = clientUser.Client,
                        ConnectionAuditLog      = auditLog,
                        TokenStartDateTimeUTC   = nowDateTime,
                        TokenEndDateTimeUTC     = tokenExpiration
                    };
                    unitOfWork.AuditRepository.CreateClientConnectionLog(newConnection);

                    //Generate claims for the token
                    var identity = new ClaimsIdentity("JWT");
                    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.Email, clientUser.Email));
                    identity.AddClaim(new Claim(ClaimTypes.Expiration, tokenExpiration.ToString()));
                    identity.AddClaim(new Claim("LogId", auditId.ToString()));
                    var tokenEnd = DateTime.UtcNow.AddSeconds(tokenTimespanSec);

                    var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    context.Validated(ticket);
                }
                catch (Exception ex)
                {
                    if (ex is AuthenticationException)
                    {
                        context.SetError("invalid_grant", ex.Message);
                    }
                    else
                    {
                        context.SetError("invalid_grant", String.Format("Internal Error (Please contact Exiger support with reference ID: {0})", auditLog.Id));
                    }
                    auditLog.ErrorMessage = ex.Message;
                }
                finally
                {
                    unitOfWork.Commit();
                }
            }
            return;
        }
Example #11
0
 public void RemoveConnection(string index, TcpClient c)
 {
     ClientConnections.Remove(index.ToUpper());
 }
Example #12
0
 public void AddConnection(string index, TcpClient c)
 {
     ClientConnections.Add(index.ToUpper(), c);
 }
Example #13
0
 public void CreateClientConnectionLog(ClientConnections clientConnection)
 {
     _repositoryBase.Add(clientConnection);
 }
Example #14
0
        /// <summary>
        /// Reads the socket.
        /// </summary>
        /// <param name="obj">The object.</param>
        private void readSocket(object obj)
        {
            //cast the obj which is a clientConnection
            ClientConnections connection = obj as ClientConnections;

            try
            {
                //size/data of read
                List <byte[]> listObject = new List <byte[]>();
                byte[]        bytes      = new byte[8192];
                byte[]        fullObjectBytes;
                NetworkStream stream = connection.cSocket.GetStream();

                //check if connection is still open
                if (connection.cSocket.Connected)
                {
                    stream.Read(bytes, 0, bytes.Length);
                }
                else
                {
                    //stop timer if connection closed
                    connection.rTimer.stop();
                }
                listObject.Add(bytes);

                //Convert data recived to an object
                var bformatter = new BinaryFormatter();
                fullObjectBytes = bytes;
                Stream fullObjectStream = new MemoryStream(fullObjectBytes);
                object objFromClient    = bformatter.Deserialize(fullObjectStream);
                Type   objType          = objFromClient.GetType();

                byte[] objectOut = new byte[0]; //temp- the file data the will be sent to client

                if (objType == typeof(String))  //client sent name
                {
                    connection.name = ((string)objFromClient);
                    objectOut       = ObjectToByteArray("Connected");
                }
                else if (objType == typeof(Answer))//client gives you an answer (give them next question or their results)
                {
                    //Send client a question
                    Answer userAnswer = (Answer)objFromClient;

                    //check if first question
                    if (connection.question != -1)
                    {
                        List <string> queryRow = db.Select("Select questionNum,question,ans1,ans2,ans3,ans4,correctAnswer from questions where questionNum = " + connection.question).FirstOrDefault();

                        QACombo QARow = new QACombo(String.Join("|", queryRow));

                        if (userAnswer.answer == QARow.correctAnswer)
                        {
                            connection.score += userAnswer.timeLeft;
                        }
                        else
                        {
                            userAnswer.timeLeft = 0;
                        }
                        //Add users answer/result to results list
                        connection.results.Add(new Result(QARow.questionNum + "|" + QARow.question + "|" + queryRow[1 + QARow.correctAnswer] + "|" + queryRow[1 + userAnswer.answer]));
                        db.Insert("INSERT INTO questionattempts (questionId,timeLeft)VALUES(" + QARow.questionNum + "," + userAnswer.timeLeft + ")");
                    }
                    //get next question data
                    List <string> nextQuestion = db.Select("Select questionNum,question,ans1,ans2,ans3,ans4,correctAnswer from questions where questionNum > " + connection.question + " Order By questionNum ASC").FirstOrDefault();
                    if (nextQuestion != null)
                    {
                        //Create object to send to client
                        QACombo nextQ = new QACombo(String.Join("|", nextQuestion));
                        objectOut = ObjectToByteArray(nextQ);

                        connection.question = nextQ.questionNum;
                    }
                    else
                    {
                        //Add user to leaderboard
                        db.Insert("INSERT INTO leaderboard (name,score)VALUES('" + connection.name + "'," + connection.score + ")");
                        objectOut = ObjectToByteArray(connection.results);
                    }
                }
                else if (objType == typeof(CurrentStatus))//
                {
                    //List of current connections
                    List <CurrentStatus> statusList = new List <CurrentStatus>();
                    foreach (var con in connections)
                    {
                        if (con.question != -1)
                        {
                            CurrentStatus newStatus;
                            newStatus.name        = con.name;
                            newStatus.score       = con.score;
                            newStatus.questionNum = con.question;
                            statusList.Add(newStatus);
                        }
                    }
                    //Send list of current connection to admin
                    objectOut = ObjectToByteArray(statusList);
                }
                else if (objType == typeof(Leaderboard))
                {
                    //create leaderboard
                    List <List <string> > leader      = db.Select("Select name, score from leaderboard order by score Desc");
                    List <Leaderboard>    leaderBoard = new List <Leaderboard>();
                    foreach (var player in leader)
                    {
                        Leaderboard newLeaderboard;
                        newLeaderboard.name  = player[0];
                        newLeaderboard.score = Convert.ToInt16(player[1]);
                        leaderBoard.Add(newLeaderboard);
                    }
                    leaderBoard.OrderBy(o => o.score).ToList();
                    //Send leaderboard to user
                    objectOut = ObjectToByteArray(leaderBoard);
                }
                else if (objType == typeof(ExcelData))
                {
                    //Create excel list for admin
                    List <ExcelData>      excelDataList = new List <ExcelData>();
                    List <List <string> > excelRecords  = db.Select("Select questionId, timeLeft from questionattempts");
                    List <List <string> > questionData  = db.Select("Select questionNum, question from questions");
                    //Combine questionatttempts and question information to generate fields for excel
                    foreach (List <string> questionRecord in questionData)
                    {
                        int    questionNumber = Convert.ToInt16(questionRecord[0]);
                        string questionText   = questionRecord[1];

                        double avgTime        = 0;
                        int    count          = 0;
                        double percentCorrect = 0;

                        foreach (var excelRecord in excelRecords)
                        {
                            if (excelRecord[0] == questionRecord[0])
                            {
                                avgTime += Convert.ToDouble(excelRecord[1]);

                                if (excelRecord[1] != "0")
                                {
                                    percentCorrect++;
                                }
                                count++;
                            }
                        }
                        avgTime = count != 0 ? avgTime /= count : 0;

                        percentCorrect  = count != 0 ? percentCorrect /= count : 0;
                        percentCorrect *= 100;

                        excelDataList.Add(new ExcelData(questionNumber, questionText, avgTime, percentCorrect));
                    }
                    //Send excel data to admin
                    objectOut = ObjectToByteArray(excelDataList);
                }

                else if (objType == typeof(List <QACombo>))
                {
                    //Admin updates the question list
                    List <QACombo> QAList = (List <QACombo>)objFromClient;
                    if (QAList.Any())                              //Admin is changing questions
                    {
                        db.Delete("DELETE FROM questions");        //Remove all questions
                        db.Delete("DELETE FROM questionattempts"); //remove all questionattempts
                        //insert all new questions
                        foreach (var record in QAList)
                        {
                            db.Insert("INSERT INTO questions (questionNum,question,ans1,ans2,ans3,ans4,correctAnswer)VALUES(" + record.questionNum + ",'" + record.question + "','" + record.ans1 + "','" + record.ans2 + "','" + record.ans3 + "','" + record.ans4 + "'," + record.correctAnswer + ")");
                        }
                    }
                    else//Read all questions
                    {
                        List <QACombo> send = new List <QACombo>();

                        List <List <string> > thisQuestion = db.Select("Select questionNum,question,ans1,ans2,ans3,ans4,correctAnswer from questions");
                        foreach (List <string> record in thisQuestion)
                        {
                            send.Add(new QACombo(String.Join("|", record)));
                        }
                        //Send all questions to admin
                        objectOut = ObjectToByteArray(send);
                    }
                }
                //Send the data to the client
                stream.Write(objectOut, 0, objectOut.Length);
            }
            catch (IOException e)
            {
                connection.cSocket.Close();
                connection.rTimer.stop();
            }
            catch (SerializationException e)
            {
                connection.cSocket.Close();
                connection.rTimer.stop();
            }
            finally
            {
                for (int i = 0; i < connections.Count; i++)
                {
                    //Check if any clients have disconnected from the server
                    if (connections[i].cSocket.Connected == false)
                    {
                        //Remove the client from running clients list
                        connections.RemoveAt(i);
                    }
                }
            }
        }