예제 #1
0
        static void Main(string[] args)
        {
            // Select the map
            int selectedMap = 0;

            string[]   mapFiles = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/../../../../Maps");
            ConsoleKey key;

            do
            {
                Console.Clear();
                for (int i = 0; i < mapFiles.Length; i++)
                {
                    Console.WriteLine("[{0}] {1}", i == selectedMap ? "X" : " ", Path.GetFileNameWithoutExtension(mapFiles[i]));
                }

                key = Console.ReadKey().Key;
                if (key == ConsoleKey.UpArrow && selectedMap > 0)
                {
                    selectedMap--;
                }
                else if (key == ConsoleKey.DownArrow && selectedMap < mapFiles.Length)
                {
                    selectedMap++;
                }
            }while (key != ConsoleKey.Enter);

            // Load the map
            var map = new TileMap();

            map.LoadMap(mapFiles[selectedMap]);
            Room = new GameRoom(map);
            Console.WriteLine("MAP LOADED");
            Timer.Start();

            server = new WebSocketServer(IPAddress.Any, 1337);
            server.AddWebSocketService <GameService>("/");
            server.Start();
            Console.ReadKey(true);
            server.Stop();
            Console.WriteLine("SERVER STOPPED");
        }
        static void Main(string[] args)
        {
            // the listener socket
            WebSocketServer server = new WebSocketServer(8080);

            server.AddWebSocketService <DemoBehaviour>("/demo");
            // server.AddWebSocketService<GameBehaviour>("/game");
            server.Start();


            bool continueRunning = true;

            while (continueRunning)
            {
                if (Console.ReadLine() == "q")
                {
                    continueRunning = false;
                }
            }
        }
예제 #3
0
        public static bool Start()
        {
            try
            {
                ws = new WebSocketServer($"ws://{Config.Host}:{Config.Port}");
            } catch (Exception e)
            {
                Console.WriteLine("Exception when starting server: \n" + e.Message);
                return(false);
            }

            // Adds overloaded WebSocketBehaviour server via generics
            ws.AddWebSocketService <Chat>("/chat");

            // Starts the websocket server
            ws.Start();

            Console.WriteLine($"Server started on {Config.Host}:{Config.Port}");
            return(true);
        }
예제 #4
0
        public void Start()
        {
            Logger.Log(this, "Started");

            Active = true;

            SocketServer       = new WebSocketServer(SettingsLoader.Values.Server.HostUrl);
            ConnectionsHandler = new ConnectionsHandler(SettingsLoader);
            RoomManager        = new RoomManager(ConnectionsHandler, SettingsLoader);

            SocketServer.Start(socket =>
            {
                socket.OnOpen  += () => ConnectionsHandler.OnOpen(socket);
                socket.OnClose += () => ConnectionsHandler.OnClose(socket);
            });

            while (Active)
            {
                CommandHandler.ParseCommand(Console.ReadLine());
            }
        }
예제 #5
0
파일: Program.cs 프로젝트: wsycarlos/ARIA
        static void Main(string[] args)
        {
            WebSocketServer appServer = new WebSocketServer();

            string ip = args[0];
            int port = int.Parse(args[1]);

            if (!appServer.Setup(ip, port))
            {
                Console.WriteLine("Failed to setup!");
                return;
            }

            appServer.NewSessionConnected += appServer_NewSessionConnected;

            appServer.NewDataReceived += appServer_NewDataReceived;

            appServer.SessionClosed += appServer_SessionClosed;

            //Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                return;
            }

            Console.WriteLine("Press Q to Stop Server");

            while (Console.ReadKey().KeyChar != 'q')
            {
                continue;
            }

            appServer.Stop();

            Console.WriteLine("The Server was Stopped!");
        }
예제 #6
0
        public static void Main(string[] args)
        {
            PoolConnectionFactory.RegisterCallbacks(PoolReceiveCallback,
                                                    PoolErrorCallback, PoolDisconnectCallback);

            if (File.Exists("statistics.dat"))
            {
                try {
                    statistics.Clear();

                    string[] lines = File.ReadAllLines("statistics.dat");

                    foreach (string line in lines)
                    {
                        string[] statisticsdata = line.Split(new string[] { SEP }, StringSplitOptions.None);

                        string statid  = statisticsdata[1];
                        long   statnum = 0;
                        long.TryParse(statisticsdata[0], out statnum);

                        statistics.TryAdd(statid, statnum);
                    }
                } catch (Exception ex) {
                    Console.WriteLine("Error while reading statistics: {0}", ex);
                }
            }

            if (File.Exists("logins.dat"))
            {
                try {
                    loginids.Clear();

                    string[] lines = File.ReadAllLines("logins.dat");

                    foreach (string line in lines)
                    {
                        string[] logindata = line.Split(new string[] { SEP }, StringSplitOptions.None);

                        Credentials cred = new Credentials();
                        cred.Pool     = logindata[1];
                        cred.Login    = logindata[2];
                        cred.Password = logindata[3];

                        loginids.TryAdd(logindata[0], cred);
                    }
                } catch (Exception ex) {
                    Console.WriteLine("Error while reading logins: {0}", ex);
                }
            }

            FillPoolPool();

            WebSocketServer server;

#if (WSS)
            X509Certificate2 cert = new X509Certificate2("certificate.pfx", "miner");

#if (AEON)
            server = new WebSocketServer("wss://0.0.0.0:8282");
#else
            server = new WebSocketServer("wss://0.0.0.0:8181");
#endif

            server.Certificate = cert;
#else
#if (AEON)
            server = new WebSocketServer("ws://0.0.0.0:8282");
#else
            server = new WebSocketServer("ws://0.0.0.0:8181");
#endif
#endif

            FleckLog.LogAction = (level, message, ex) => {
                switch (level)
                {
                case LogLevel.Debug:
#if (DEBUG)
                    Console.WriteLine("FLECK (Debug): " + message);
#endif
                    break;

                case LogLevel.Error:
                    if (ex != null && !string.IsNullOrEmpty(ex.Message))
                    {
                        Console.WriteLine("FLECK: " + message + " " + ex.Message);

                        exceptionCounter++;
                        if ((exceptionCounter % 200) == 0)
                        {
                            Helper.WriteTextAsyncWrapper("fleck_error.txt", ex.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("FLECK: " + message);
                    }
                    break;

                case LogLevel.Warn:
                    if (ex != null && !string.IsNullOrEmpty(ex.Message))
                    {
                        Console.WriteLine("FLECK: " + message + " " + ex.Message);

                        exceptionCounter++;
                        if ((exceptionCounter % 200) == 0)
                        {
                            Helper.WriteTextAsyncWrapper("fleck_warn.txt", ex.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("FLECK: " + message);
                    }
                    break;

                default:
                    Console.WriteLine("FLECK: " + message);
                    break;
                }
            };

            server.RestartAfterListenError = true;
            server.ListenerSocket.NoDelay  = false;

            server.Start(socket => {
                socket.OnOpen = () => {
                    string ipadr = string.Empty;
                    try { ipadr = socket.ConnectionInfo.ClientIpAddress; } catch { }

                    Client client    = new Client();
                    client.WebSocket = socket;
                    client.Created   = client.LastPoolJobTime = DateTime.Now;

                    Guid guid = socket.ConnectionInfo.Id;
                    clients.TryAdd(guid, client);

                    Console.WriteLine("{0}: connected with ip {1}", guid, ipadr);
                };
                socket.OnClose = () => {
                    Guid guid = socket.ConnectionInfo.Id;
                    RemoveClient(socket.ConnectionInfo.Id);

                    Console.WriteLine(guid + ": closed");
                };
                socket.OnError = error => {
                    Guid guid = socket.ConnectionInfo.Id;
                    RemoveClient(socket.ConnectionInfo.Id);

                    Console.WriteLine(guid + ": unexpected close");
                };
                socket.OnMessage = message => {
                    string ipadr = string.Empty;
                    try { ipadr = socket.ConnectionInfo.ClientIpAddress; } catch { }

                    Guid guid = socket.ConnectionInfo.Id;

                    if (message.Length > 3000)
                    {
                        RemoveClient(guid);  // that can't be valid, do not even try to parse
                    }

                    JsonData msg = message.FromJson <JsonData> ();
                    if (msg == null || !msg.ContainsKey("identifier"))
                    {
                        return;
                    }

                    Client client = null;

                    // in very rare occasions, we get interference with onopen()
                    // due to async code. wait a second and retry.
                    for (int tries = 0; tries < 4; tries++)
                    {
                        if (clients.TryGetValue(guid, out client))
                        {
                            break;
                        }
                        Task.Run(async delegate { await Task.Delay(TimeSpan.FromSeconds(1)); }).Wait();
                    }

                    if (client == null)
                    {
                        // famous comment: this should not happen
                        RemoveClient(guid);
                        return;
                    }

                    string identifier = (string)msg["identifier"];

                    if (identifier == "handshake")
                    {
                        if (client.GotHandshake)
                        {
                            // no merci for malformed data.
                            DisconnectClient(client, "Handshake already performed.");
                            return;
                        }

                        client.GotHandshake = true;

                        if (msg.ContainsKey("version"))
                        {
                            int.TryParse(msg["version"].GetString(), out client.Version);
                        }

                        if (msg.ContainsKey("loginid"))
                        {
                            string loginid = msg["loginid"].GetString();

                            if (loginid.Length != 36 && loginid.Length != 32)
                            {
                                Console.WriteLine("Invalid LoginId!");
                                DisconnectClient(client, "Invalid loginid.");
                                return;
                            }

                            Credentials crdts;
                            if (!loginids.TryGetValue(loginid, out crdts))
                            {
                                Console.WriteLine("Unregistered LoginId! {0}", loginid);
                                DisconnectClient(client, "Loginid not registered!");
                                return;
                            }

                            client.Login    = crdts.Login;
                            client.Password = crdts.Password;
                            client.Pool     = crdts.Pool;
                        }
                        else if (msg.ContainsKey("login") && msg.ContainsKey("password") && msg.ContainsKey("pool"))
                        {
                            client.Login    = msg["login"].GetString();
                            client.Password = msg["password"].GetString();
                            client.Pool     = msg["pool"].GetString();
                        }
                        else
                        {
                            // no merci for malformed data.
                            Console.WriteLine("Malformed handshake");
                            DisconnectClient(client, "Login, password and pool have to be specified.");
                            return;
                        }

                        client.UserId = string.Empty;

                        if (msg.ContainsKey("userid"))
                        {
                            string uid = msg["userid"].GetString();

                            if (uid.Length > 200)
                            {
                                RemoveClient(socket.ConnectionInfo.Id); return;
                            }
                            client.UserId = uid;
                        }

                        Console.WriteLine("{0}: handshake - {1}", guid, client.Pool);

                        if (!string.IsNullOrEmpty(ipadr))
                        {
                            Firewall.Update(ipadr, Firewall.UpdateEntry.Handshake);
                        }

                        PoolInfo pi;

                        if (!PoolPool.TryGetValue(client.Pool, out pi))
                        {
                            // we dont have that pool?
                            DisconnectClient(client, "pool not known");
                            return;
                        }

                        // if pools have some default password
                        if (client.Password == "")
                        {
                            client.Password = pi.EmptyPassword;
                        }

                        client.PoolConnection = PoolConnectionFactory.CreatePoolConnection(
                            client, pi.Url, pi.Port, client.Login, client.Password);
                    }
                    else if (identifier == "solved")
                    {
                        if (!client.GotHandshake)
                        {
                            // no merci
                            RemoveClient(socket.ConnectionInfo.Id);
                            return;
                        }

                        Console.WriteLine("{0}: reports solved hash", guid);

                        new Task(() => {
                            if (!msg.ContainsKey("job_id") ||
                                !msg.ContainsKey("nonce") ||
                                !msg.ContainsKey("result"))
                            {
                                // no merci for malformed data.
                                RemoveClient(guid);
                                return;
                            }

                            string jobid = msg["job_id"].GetString();

                            JobInfo ji;

                            if (!jobInfos.TryGetValue(jobid, out ji))
                            {
                                // this job id is not known to us
                                Console.WriteLine("Job unknown!");
                                return;
                            }

                            string reportedNonce  = msg["nonce"].GetString();
                            string reportedResult = msg["result"].GetString();

                            if (ji.Solved.Contains(reportedNonce.ToLower()))
                            {
                                Console.WriteLine("Nonce collision!");
                                return;
                            }

                            if (reportedNonce.Length != 8 || (!Regex.IsMatch(reportedNonce, RegexIsHex)))
                            {
                                DisconnectClient(client, "nonce malformed");
                                return;
                            }

                            if (reportedResult.Length != 64 || (!Regex.IsMatch(reportedResult, RegexIsHex)))
                            {
                                DisconnectClient(client, "result malformed");
                                return;
                            }

                            double prob        = ((double)HexToUInt32(ji.Target)) / ((double)0xffffffff);
                            long howmanyhashes = ((long)(1.0 / prob));

                            totalHashes += howmanyhashes;

                            if (ji.OwnJob)
                            {
                                // that was an "own" job. could be that the target does not match

                                if (!CheckHashTarget(ji.Target, reportedResult))
                                {
                                    Console.WriteLine("Hash does not reach our target difficulty.");
                                    return;
                                }

                                totalOwnHashes += howmanyhashes;
                            }

                            // default chance to get hash-checked is 10%
                            double chanceForACheck = 0.1;

                            // check new clients more often, but prevent that to happen the first 30s the server is running
                            if (Hearbeats > 3 && client.NumChecked < 9)
                            {
                                chanceForACheck = 1.0 - 0.1 * client.NumChecked;
                            }

                            bool performFullCheck = (rnd.NextDouble() < chanceForACheck && HashesCheckedThisHeartbeat < MaxHashChecksPerHeartbeat);

                            if (performFullCheck)
                            {
                                client.NumChecked++;
                                HashesCheckedThisHeartbeat++;
                            }

                            bool validHash = CheckHash(ji.Blob, reportedNonce, ji.Target, reportedResult, performFullCheck);

                            if (!validHash)
                            {
                                Console.WriteLine("{0} got disconnected for WRONG HASH.", client.WebSocket.ConnectionInfo.Id.ToString());

                                if (!string.IsNullOrEmpty(ipadr))
                                {
                                    Firewall.Update(ipadr, Firewall.UpdateEntry.WrongHash);
                                }
                                RemoveClient(client.WebSocket.ConnectionInfo.Id);
                            }
                            else
                            {
                                if (performFullCheck)
                                {
                                    Console.WriteLine("{0}: got hash-checked", client.WebSocket.ConnectionInfo.Id.ToString());
                                }

                                if (!string.IsNullOrEmpty(ipadr))
                                {
                                    Firewall.Update(ipadr, Firewall.UpdateEntry.SolvedJob);
                                }

                                ji.Solved.TryAdd(reportedNonce.ToLower());

                                if (client.UserId != string.Empty)
                                {
                                    long currentstat = 0;

                                    bool exists = statistics.TryGetValue(client.UserId, out currentstat);

                                    if (exists)
                                    {
                                        statistics[client.UserId] = currentstat + howmanyhashes;
                                    }
                                    else
                                    {
                                        statistics.TryAdd(client.UserId, howmanyhashes);
                                    }
                                }

                                if (!ji.OwnJob)
                                {
                                    client.PoolConnection.Hashes += howmanyhashes;
                                }

                                Client jiClient = client;
                                if (ji.OwnJob)
                                {
                                    jiClient = ourself;
                                }

                                string msg1 = "{\"id\":\"" + jiClient.PoolConnection.PoolId +
                                              "\",\"job_id\":\"" + ji.InnerId +
                                              "\",\"nonce\":\"" + msg["nonce"].GetString() +
                                              "\",\"result\":\"" + msg["result"].GetString() +
                                              "\"}";

                                string msg0 = "{\"method\":\"" + "submit" +
                                              "\",\"params\":" + msg1 +
                                              ",\"id\":\"" + "1" + "\"}\n"; // TODO: check the "1"

                                jiClient.PoolConnection.Send(jiClient, msg0);
                            }
                        }).Start();
                    }
                    else if (identifier == "poolinfo")
                    {
                        if (!client.GotPoolInfo)
                        {
                            client.GotPoolInfo = true;
                            client.WebSocket.Send(jsonPools);
                        }
                    }
                    else
                    if (identifier == "register")
                    {
                        string registerip = string.Empty;

                        try { registerip = client.WebSocket.ConnectionInfo.ClientIpAddress; } catch { };

                        if (string.IsNullOrEmpty(registerip))
                        {
                            DisconnectClient(guid, "Unknown error."); return;
                        }

                        int registeredThisSession = 0;
                        if (credentialSpamProtector.TryGetValue(registerip, out registeredThisSession))
                        {
                            registeredThisSession++;
                            credentialSpamProtector[registerip] = registeredThisSession;
                        }
                        else
                        {
                            credentialSpamProtector.TryAdd(registerip, 0);
                        }

                        if (registeredThisSession > 10)
                        {
                            DisconnectClient(guid, "Too many registrations. You need to wait.");
                            return;
                        }

                        if (!msg.ContainsKey("login") ||
                            !msg.ContainsKey("password") ||
                            !msg.ContainsKey("pool"))
                        {
                            // no merci for malformed data.
                            DisconnectClient(guid, "Login, password and pool have to be specified!");
                            return;
                        }

                        // everything seems to be okay
                        Credentials crdts = new Credentials();
                        crdts.Login       = msg["login"].GetString();
                        crdts.Pool        = msg["pool"].GetString();
                        crdts.Password    = msg["password"].GetString();

                        PoolInfo pi;

                        if (!PoolPool.TryGetValue(crdts.Pool, out pi))
                        {
                            // we dont have that pool?
                            DisconnectClient(client, "Pool not known!");
                            return;
                        }

                        bool loginok = false;
                        try { loginok = Regex.IsMatch(crdts.Login, RegexIsXMR); } catch { }

                        if (!loginok)
                        {
                            DisconnectClient(client, "Not a valid address.");
                            return;
                        }

                        if (crdts.Password.Length > 120)
                        {
                            DisconnectClient(client, "Password too long.");
                            return;
                        }

                        string newloginguid = Guid.NewGuid().ToString("N");
                        loginids.TryAdd(newloginguid, crdts);

                        string smsg = "{\"identifier\":\"" + "registered" +
                                      "\",\"loginid\":\"" + newloginguid +
                                      "\"}";

                        client.WebSocket.Send(smsg);

                        Console.WriteLine("Client registered!");

                        saveLoginIdsNextHeartbeat = true;
                    }
                    else if (identifier == "userstats")
                    {
                        if (!msg.ContainsKey("userid"))
                        {
                            return;
                        }

                        Console.WriteLine("Userstat request");

                        string uid = msg["userid"].GetString();

                        long hashn = 0;
                        statistics.TryGetValue(uid, out hashn);

                        string smsg = "{\"identifier\":\"" + "userstats" +
                                      "\",\"userid\":\"" + uid +
                                      "\",\"value\":" + hashn.ToString() + "}\n";

                        client.WebSocket.Send(smsg);
                    }
                };
            });

            bool running = true;

            double totalspeed = 0, totalownspeed = 0;

            while (running)
            {
                Hearbeats++;

                Firewall.Heartbeat(Hearbeats);

                try {
                    if (Hearbeats % SaveStatisticsEveryXHeartbeat == 0)
                    {
                        Console.WriteLine("Saving statistics...");

                        StringBuilder sb = new StringBuilder();

                        foreach (var stat in statistics)
                        {
                            sb.AppendLine(stat.Value.ToString() + SEP + stat.Key);
                        }

                        File.WriteAllText("statistics.dat", sb.ToString().TrimEnd('\r', '\n'));

                        Console.WriteLine("done.");
                    }
                } catch (Exception ex) {
                    Console.WriteLine("Error saving statistics.dat: {0}", ex);
                }

                try {
                    if (saveLoginIdsNextHeartbeat)
                    {
                        saveLoginIdsNextHeartbeat = false;
                        Console.WriteLine("Saving logins...");

                        StringBuilder sb = new StringBuilder();

                        foreach (var lins in loginids)
                        {
                            sb.AppendLine(lins.Key + SEP + lins.Value.Pool + SEP + lins.Value.Login + SEP + lins.Value.Password);
                        }

                        File.WriteAllText("logins.dat", sb.ToString().TrimEnd('\r', '\n'));

                        Console.WriteLine("done.");
                    }
                }  catch (Exception ex) {
                    Console.WriteLine("Error saving logins.dat: {0}", ex);
                }

                try {
                    Task.Run(async delegate { await Task.Delay(TimeSpan.FromSeconds(HeartbeatRate)); }).Wait();

                    if (Hearbeats % SpeedAverageOverXHeartbeats == 0)
                    {
                        totalspeed    = (double)totalHashes / (double)(HeartbeatRate * SpeedAverageOverXHeartbeats);
                        totalownspeed = (double)totalOwnHashes / (double)(HeartbeatRate * SpeedAverageOverXHeartbeats);

                        totalHashes    = 0;
                        totalOwnHashes = 0;
                    }

                    Console.WriteLine("[{0}] heartbeat, connections: client {1}, pool {2}, jobqueue: {3}, total/own: {4}/{5} h/s", DateTime.Now.ToString(),
                                      clients.Count, PoolConnectionFactory.Connections.Count, jobQueue.Count, totalspeed, totalownspeed);

                    while (jobQueue.Count > JobCacheSize)
                    {
                        string deq;
                        if (jobQueue.TryDequeue(out deq))
                        {
                            jobInfos.TryRemove(deq);
                        }
                    }

                    DateTime now = DateTime.Now;

                    List <PoolConnection> pcc = new List <PoolConnection> (PoolConnectionFactory.Connections.Values);
                    foreach (PoolConnection pc in pcc)
                    {
                        PoolConnectionFactory.CheckPoolConnection(pc);
                    }

                    List <Client> cc = new List <Client> (clients.Values);

                    foreach (Client c in cc)
                    {
                        try {
                            if ((now - c.Created).TotalSeconds > GraceConnectionTime)
                            {
                                if (c.PoolConnection == null || c.PoolConnection.TcpClient == null)
                                {
                                    DisconnectClient(c, "timeout.");
                                }
                                else if (!c.PoolConnection.TcpClient.Connected)
                                {
                                    DisconnectClient(c, "lost pool connection.");
                                }
                                else if ((now - c.LastPoolJobTime).TotalSeconds > PoolTimeout)
                                {
                                    DisconnectClient(c, "pool is not sending new jobs.");
                                }
                            }
                        } catch { RemoveClient(c.WebSocket.ConnectionInfo.Id); }
                    }

                    if (clients.ContainsKey(Guid.Empty))
                    {
                        if (clients.Count == 1)
                        {
                            RemoveClient(Guid.Empty);
                        }
                    }
                    else
                    {
                        // we removed ourself because we got disconnected from the pool
                        // make us alive again!
                        if (clients.Count > 0)
                        {
                            Console.WriteLine("disconnected from own pool. trying to reconnect.");
                            ownJob = new Job();
                            CreateOurself();
                        }
                    }

                    HashesCheckedThisHeartbeat = 0;

                    if (Hearbeats % ForceGCEveryXHeartbeat == 0)
                    {
                        Console.WriteLine("Garbage collection. Currently using {0} MB.", Math.Round(((double)(GC.GetTotalMemory(false)) / 1024 / 1024)));

                        DateTime tbc = DateTime.Now;

                        // trust me, I am a professional
                        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);  // DON'T DO THIS!!!
                        Console.WriteLine("Garbage collected in {0} ms. Currently using {1} MB ({2} clients).", (DateTime.Now - tbc).Milliseconds,
                                          Math.Round(((double)(GC.GetTotalMemory(false)) / 1024 / 1024)), clients.Count);
                    }
                } catch (Exception ex) {
                    Console.WriteLine("{0} Exception caught in the main loop !", ex);
                }
            }
        }
예제 #7
0
 public void Start()
 {
     webSocketServer.Start();
 }
예제 #8
0
        static void Main(string[] args)
        {
            // INit DB
            //    Utility.LaunchDB();

            LoLClient lol = new LoLClient();

            lol.GetSummonerIdByName("Hades Underworld");
            //lol.GetSummonerMatchesById();
            lol.GetSummonerRankingById();
            lol.GetSummonerGamesById();

            LoLGTContext context = new LoLGTContext();

            //   context.
            //context.Matches.Add(lol.Matches);
            context.StatsRanking.Add(lol.Ranking);
            context.SummonerGames.Add(lol.SummonerGames);
            context.SaveChanges();
            DateTime timeAtSendToClients = new DateTime();
            DateTime timeNow             = new DateTime();
            // ↓ Connect to ipaddress:4649/SendData
            WebSocketServer wssv = new WebSocketServer(System.Net.IPAddress.Any, 4649);

#if DEBUG
            wssv.Log.Level = LogLevel.Trace;
#endif
            wssv.KeepClean    = true;
            wssv.WaitTime     = TimeSpan.FromSeconds(120);
            wssv.ReuseAddress = false;
            // ↓ Implement Server activies in SendData.cs
            wssv.AddWebSocketService <SendData>("/SendData");

            //     LoLClient lol = new LoLClient();

            Console.WriteLine();

            wssv.Start();
            timeAtSendToClients = DateTime.Now;

            string input = "";
            while (input != "stop")
            {
                //timeNow = DateTime.Now;
                //if (timeNow == timeAtSendToClients+TimeSpan.FromMinutes(5))
                //{
                //    // ↓ Tony add the data to send to the clients in SendData
                //    string dataToBroadcast = "";
                //    wssv.WebSocketServices["/SendData"].Sessions.Broadcast(dataToBroadcast);
                //}
                //if (input.Take(5).ToString().ToLower() == "send ")
                //{
                //    string dataToBroadcast = input.Skip(5).ToString();
                //    wssv.WebSocketServices["/SendData"].Sessions.Broadcast(dataToBroadcast);
                //}

                input = "";
                try
                {
                    input = ReaderForLoops.ReadLine(150000);
                }
                catch (TimeoutException)
                {
                    //Console.WriteLine("Next loop init");
                }
            }
            wssv.Stop();
        }
예제 #9
0
        public Form1()
        {
            InitializeComponent();

            //when requesting sockets change, clear and display requests
            requestingSockets.CollectionChanged += (s, e) =>
            {
                //remove all requesting controls
                //foreach (Control item in Controls)
                //{
                //if (item.Name.Equals("request"))
                //Invoke(new Action(() => { Controls.Remove(item); }));
                //}

                for (int i = 0; i < Controls.Count; i++)
                {
                    if (Controls[i].Name.Equals("request"))
                    {
                        Invoke(new Action(() => { Controls.Remove(Controls[i]); }));
                        i--; //subtract one because by removing a control, just decreased the controls list count, could create list of controls to remove then remove after instead
                    }
                }

                //displays requesting controls
                DisplayRequestingSockets();
            };

            server = new WebSocketServer("ws://10.92.84.183:80");

            server.Start((socket) =>
            {
                //when a client socket connects
                socket.OnOpen = () =>
                {
                    Invoke(new Action(() => { rtbMessages.AppendText(String.Format("{0} connected.", socket.ConnectionInfo.Id) + Environment.NewLine); }));
                    sockets.Add(socket); //add client socket new list
                };

                //when a client socket disconnects
                socket.OnClose = () =>
                {
                    Invoke(new Action(() => { rtbMessages.AppendText(String.Format("{0} disconnected.", socket.ConnectionInfo.Id) + Environment.NewLine); }));
                    sockets.Remove(socket);           //remove client socket from list
                    requestingSockets.Remove(socket); //remove client socket from requesitng list too

                    //if disconnected socket is current speaker, set current speaker to null (none)
                    if (currentSpeaker == socket)
                    {
                        currentSpeaker = null;
                    }
                };

                //when the sv receives a message from a client
                socket.OnMessage = (message) =>
                {
                    RootObject root = JsonConvert.DeserializeObject <RootObject>(message); //deserialize json message into obj

                    switch (root.Data.Type)
                    {
                    case "request":
                        Invoke(new Action(() => { rtbMessages.AppendText(socket.ConnectionInfo.Id + " wants to speak." + Environment.NewLine); }));

                        //add socket to requesting to speak
                        requestingSockets.Add(socket);
                        break;
                    }
                };
            });

            //sends message to all clients
            btnPing.Click += (s, e) =>
            {
                foreach (var socket in sockets)
                {
                    RootObject root = new RootObject();
                    root.Data.Type    = "ping";
                    root.Data.Message = "Server ping.";
                    string json = JsonConvert.SerializeObject(root);
                    socket.Send(json);
                }
            };

            //turn off current speaker mic = no current speaker
            btnTurnOffCurrentSpeaker.Click += (s, e) =>
            {
                currentSpeaker = null;
            };

            rtbMessages.AppendText("Server started." + Environment.NewLine);
        }
 public NetworkHandlerServer()
 {
     wss = new WebSocketServer("ws://localhost:2411");
     wss.AddWebSocketService <ServerResponse>("/Tester");
     wss.Start();
 }