Esempio n. 1
0
        /// <summary>
        /// Calculates the main expression.
        /// </summary>
        private void CalculateMainExpression()
        {
            Thread.Sleep(2000);
            if (expressionList.Count == expressionThread.Count)
            {
                CurrentThreadDetails currentThreadDetails = new CurrentThreadDetails();
                StringBuilder        mainExpression       = new StringBuilder();
                //create main expression from polled expression
                while (!expressionList.IsEmpty)
                {
                    string expression = string.Empty;
                    expressionList.TryTake(out expression);
                    mainExpression.Append(expression);
                }
                finalAnswer = new DataTable().Compute(mainCopy + mainExpression, null);
                if (this.label1.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(SetText);
                    string          responseMessage = "MainExpression " + mainCopy + mainExpression + " =" + finalAnswer.ToString();
                    this.Invoke(d, new object[] { responseMessage });
                }

                if (finalAnswer.ToString() != "∞")
                {
                    //set final answer to all client
                    while (!expressionThread.IsEmpty)
                    {
                        expressionThread.TryDequeue(out currentThreadDetails);
                        currentThreadDetails.WaitRequestHandle.Set();
                    }
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Handles the Click event of the btnPoll control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void btnPoll_Click(object sender, EventArgs e)
        {
            CurrentThreadDetails currentThreadDetails = new CurrentThreadDetails();

            if (runningThread.Count == 0)
            {
                runningThread = backupThread;
            }
            while (!runningThread.IsEmpty)
            {
                runningThread.TryDequeue(out currentThreadDetails);
                backupThread.Enqueue(currentThreadDetails);
                currentThreadDetails.WaitRequestHandle.Set();
            }

            int i = 0;

            if (i <= 1)
            {
                //Start calculate expression thread
                Thread calculateThread = new Thread(() => CalculateMainExpression());
                calculateThread.Start();
            }
            i++;
        }
Esempio n. 3
0
        /// <summary>
        /// Register client, send poll request
        /// </summary>
        public void ServeRequest(TcpClient currentClient)
        {
            TcpClient tcpClientSocket = currentClient;
            string    clientName      = string.Empty;

            while (true)
            {
                try
                {
                    if (tcpClientSocket.Connected)
                    {
                        //Get message from socket
                        NetworkStream networkStream = tcpClientSocket.GetStream();
                        byte[]        message       = new byte[tcpClientSocket.ReceiveBufferSize];
                        networkStream.Read(message, 0, message.Length);
                        string   clientData = System.Text.Encoding.ASCII.GetString(message);
                        string[] message1   = clientData.Split('\n');
                        //TcpClient sends empty message while disconnects
                        if (message[0] == 0)
                        {
                            if (this.label1.InvokeRequired)
                            {
                                SetTextCallback d = new SetTextCallback(SetText);
                                string          responseMessage = "Client " + clientName + " has disconnected successfully.";
                                this.Invoke(d, new object[] { responseMessage });
                                currentClient.Close();
                                //Remove client from connected client queue
                                CurrentThreadDetails currentThreadDetails = new CurrentThreadDetails();
                                while (!runningThread.IsEmpty)
                                {
                                    runningThread.TryDequeue(out currentThreadDetails);
                                    if (currentThreadDetails.ClientName != clientName)
                                    {
                                        backupThread.Enqueue(currentThreadDetails);
                                    }
                                }
                                runningThread = backupThread;
                            }
                        }
                        else
                        {
                            JObject json = JObject.Parse(message1.Last());
                            clientName = json["ClientName"].ToString();
                            if (json["Expression"] == null)
                            {
                                if (this.label1.InvokeRequired)
                                {
                                    SetTextCallback d = new SetTextCallback(SetText);
                                    string          responseMessage = "Client " + json["ClientName"] + " has registered successfully.";
                                    this.Invoke(d, new object[] { responseMessage });
                                    SendMessage(responseMessage, networkStream);
                                    AutoResetEvent       waitRequestHandle    = new AutoResetEvent(false);
                                    CurrentThreadDetails currentThreadDetails = new CurrentThreadDetails();
                                    currentThreadDetails.ClientName        = json["ClientName"].ToString();
                                    currentThreadDetails.WaitRequestHandle = waitRequestHandle;
                                    runningThread.Enqueue(currentThreadDetails);
                                    ///Send poll request
                                    if (waitRequestHandle.WaitOne())
                                    {
                                        string registerRequest = HttpMessageFormat.HttpMessageBody.Replace("{Response}", "Poll");
                                        string contnentLength  = HttpMessageFormat.HttpMessageContentLength.Replace("{Length}", registerRequest.Length.ToString());
                                        byte[] responseStream  = System.Text.Encoding.ASCII.GetBytes(HttpMessageFormat.HttpMessagResponseHeader + HttpMessageFormat.HttpMessageContentType
                                                                                                     + contnentLength + HttpMessageFormat.HttpMessageResponseDate.Replace("{Date}", DateTime.Now.ToString("ddd, dd MMM yyy HH:mm:ss GMT")) + registerRequest);
                                        networkStream.Write(responseStream, 0, responseStream.Length);
                                        continue;
                                    }
                                }
                            }
                            //Get expression
                            else
                            {
                                expressionList.Add(json["Expression"].ToString());
                                if (this.label1.InvokeRequired)
                                {
                                    SetTextCallback d = new SetTextCallback(SetText);
                                    string          responseMessage = "Client " + clientName + " :" + json["Expression"].ToString();
                                    this.Invoke(d, new object[] { responseMessage });
                                }
                                AutoResetEvent       waitRequestHandle1   = new AutoResetEvent(false);
                                CurrentThreadDetails currentThreadDetails = new CurrentThreadDetails();
                                currentThreadDetails.WaitRequestHandle = waitRequestHandle1;
                                currentThreadDetails.ClientName        = clientName;
                                expressionThread.Enqueue(currentThreadDetails);

                                //wait for calculation of merged expression
                                if (waitRequestHandle1.WaitOne())
                                {
                                    //send  answer to client
                                    string registerRequest = HttpMessageFormat.HttpMessageBody.Replace("{Response}", finalAnswer.ToString());
                                    string contnentLength  = HttpMessageFormat.HttpMessageContentLength.Replace("{Length}", registerRequest.Length.ToString());
                                    byte[] responseStream  = System.Text.Encoding.ASCII.GetBytes(HttpMessageFormat.HttpMessagResponseHeader + HttpMessageFormat.HttpMessageContentType
                                                                                                 + contnentLength + HttpMessageFormat.HttpMessageResponseDate.Replace("{Date}", DateTime.Now.ToString("ddd, dd MMM yyy HH:mm:ss GMT")) + registerRequest);
                                    networkStream.Write(responseStream, 0, responseStream.Length);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (this.label1.InvokeRequired)
                    {
                        SetTextCallback d = new SetTextCallback(SetText);
                        this.Invoke(d, new object[] { ex.Message });
                    }
                }
            }
        }