private void Send_Click(object sender, EventArgs e) { // Set button state to false SendBtn.Enabled = false; // Create a new equation object from the given data Equations equation = new Equations(Convert.ToInt32(textBoxFnumber.Text), Convert.ToInt32(textBoxSnumber.Text), comboBoxOperators.Text, Convert.ToInt32(textBoxAnumber.Text), false); try { // Serialize the object into a json string and send the data to the client string json = JsonConvert.SerializeObject(equation); var sendData = Encoding.ASCII.GetBytes(json); clientSocket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, SendCallback, null); } catch (NullReferenceException) { MessageBox.Show("Unable to send message, there is no client connected.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); SendBtn.Enabled = true; } // Add equation to list to be displayed equations.Insert(0, equation); RefreshResultDatagrid(); }
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); } }