예제 #1
0
        private void ReceiveCallback(IAsyncResult AR)
        {
            try
            {
                // Socket exception will raise here when client closes
                int received = clientSocket.EndReceive(AR);

                if (received == 0)
                {
                    return;
                }

                // The received data is deserialized in the EquationProperties.
                string message = Encoding.ASCII.GetString(buffer);
                // Any excess characters are stipped of the end
                int index = message.IndexOf("}");
                message = message.Substring(0, index + 1);
                // Deserialize the json string into the equation object
                equation = JsonConvert.DeserializeObject <Equations>(message);

                // Create new node and add to nodelist
                Invoke((Action) delegate
                {
                    LinkListNode node = new LinkListNode(equation);
                    equationNodeList.AddEquationNode(node);
                });

                //add the node to the binary tree
                if (tree.root == null)
                {
                    //if tree is emtpy, set the node as the root
                    tree.root = new BinaryTreeNode(equation);
                }
                else
                {
                    //add the node to the bindary tree
                    tree.Add(equation);
                }

                Invoke((Action) delegate
                {
                    rtbAsked.Clear();
                    //the default print order for the binary tree is in-order
                    //rtbAsked.Text = BinaryTree.PrintInOrder(tree);
                    SendBtn.Enabled = true;
                });

                // Check if answer is incorrect
                if (equation.IsCorrect == false)
                {
                    Invoke((Action) delegate
                    {
                        if (equation.IsCorrect == false)
                        {
                            rtbWrong.Text = InstructorController.PrintLinkList(equationNodeList);
                        }
                    });
                }

                // Start receiving data again.
                clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
            }
            // Avoid catching all exceptions handling in cases like these.
            catch (SocketException ex)
            {
                ShowErrorDialog(ex.Message);
                Invoke((Action) delegate
                {
                    //lbl_clientCount.Text = "No connected clients";
                });
            }
            catch (ObjectDisposedException ex)
            {
                ShowErrorDialog(ex.Message);
            }
        }