Esempio n. 1
0
        /// <summary>
        /// Generates a random code. This is different each time.
        /// </summary>
        /// <returns>The new code.</returns>
        public static String GenerateCode()
        {
            PairingCodeGenerator.random = new Random();
            String code = "";

            for (int i = 0; i < Constants.SERVER_PAIRINGCODELENGTH; i++)
            {
                code += PairingCodeGenerator.GenerateChar();
            }

            return(code);
        }
        /// <summary>
        /// Main working routine
        /// </summary>
        private void Run()
        {
            // generate a new pairing code
            this.pairingCode = PairingCodeGenerator.GenerateCode();
            // send a new notification to listeners
            this.OnStarted();

            try
            {
                // create the listening server socket
                this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // bind it to the address
                this.serverSocket.Bind(new IPEndPoint(IPAddress.Any, Constants.SERVER_PORT));
                this.serverSocket.Listen(1);
                // begin async accept routine
                this.BeginAcceptClient();

                // FOREVER!
                while (true)
                {
                    // do some work
                    if (!this.AnnounceOrHandle())
                    {
                        // or else, if 'false' is returned,
                        // just chill a moment because obviously
                        // there's nothing to do and we really
                        // don't want to waste precious CPU
                        // time for something like PowerPoint
                        // right?
                        Thread.Sleep(500);
                    }
                }
            }
            catch (ThreadInterruptedException)
            {
                // aborted, it's okay
                // but close the sockets properly
                this.serverSocket.Close();
                if (this.clientSocket != null)
                {
                    this.clientSocket.Close();
                    this.clientSocket = null;
                }
            }
            finally
            {
                // always send notification
                this.OnStopped();
            }
        }