Continuous message sending on client side

We will modify the server‑side code from the previous section to continuously receive messages sent by clients, with multi‑threading enabled.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TcpServerDemo
{
    public partial class Form1 : Form
    {
        private TcpListener listener;
        private TcpClient tcpClient;

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            Thread acceptThread = new Thread(() =>
            {
                IPAddress ip = IPAddress.Parse(this.textBoxIP.Text);//Create IP instance
                listener = new TcpListener(ip, Convert.ToInt32(this.textBoxPort.Text));//Initialize TCP listener
                listener.Start();
                this.textBoxInfo.Text = "Server Started‑" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
                tcpClient = listener.AcceptTcpClient();//Blocking call, waiting for incoming connections
                this.textBoxInfo.Text = "Connection Established‑" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;

                NetworkStream stream = tcpClient.GetStream();
                byte[] byteArray = new byte[1024];
                while (true)
                {
                    int length = stream.Read(byteArray, 0, 1024);//Read stream bytes into byteArray buffer
                    //length returns the actual number of bytes transmitted from client
                    string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);
                    this.textBoxInfo.Text = "Received:" + receiveMessage + "-" +
                        DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
                }
            });
            acceptThread.IsBackground = true;
            acceptThread.Start();
        }
    }
}Code language: C# (cs)

Implementation based on WinForms + TcpClient / TcpListener:
The client keeps sending custom text inputs to server; type 【Exit】to close connection and terminate the program

This demo uses a simple workaround for multi‑threading UI freeze issues. However, the proper implementation is shown below:
Control.CheckForIllegalCrossThreadCalls = false; is a discouraged brute‑force hack. Production‑grade code should adopt Invoke/BeginInvoke for cross‑thread UI updates.

1. Server‑Side Implementation

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace TcpServerDemo
{
    public partial class Form1 : Form
    {
        private TcpListener listener;
        private TcpClient tcpClient;

        public Form1()
        {
            InitializeComponent();
            // Not for production use, for learning purpose only
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            // Spawn new thread to prevent UI thread blocking
            new Thread(() =>
            {
                IPAddress ip = IPAddress.Parse(textBoxIP.Text);
                listener = new TcpListener(ip, Convert.ToInt32(textBoxPort.Text));
                listener.Start();
                AppendLog($"Server Started‑{DateTime.Now.ToShortTimeString()}");

                tcpClient = listener.AcceptTcpClient();
                AppendLog($"Client Connected‑{DateTime.Now.ToShortTimeString()}");

                NetworkStream stream = tcpClient.GetStream();
                byte[] byteArray = new byte[1024];
                while (true)
                {
                    int length = stream.Read(byteArray, 0, 1024);
                    if (length <= 0)
                    {
                        AppendLog("Client connection dropped");
                        break;
                    }
                    string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);
                    AppendLog($"Received:{receiveMessage}{DateTime.Now.ToShortTimeString()}");
                }
                tcpClient.Close();
                listener.Stop();
            }).Start();
        }

        // Append log entry to textbox
        private void AppendLog(string msg)
        {
            textBoxInfo.Text = msg + "\r\n" + textBoxInfo.Text;
        }
    }
}Code language: C# (cs)

2. Client‑Side Code

Implements continuous input; typing “Exit” terminates communication

Suggested UI controls for client form:

  • textBoxServerIp:Server IP address
  • textBoxPort:Port number
  • textBoxSend:Input box for outgoing messages
  • btnConnect:Connect button
  • btnSend:Send button
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TcpClientDemo
{
    public partial class ClientForm : Form
    {
        private TcpClient client;
        private NetworkStream stream;
        private bool isConnected = false;

        public ClientForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        // Connect to remote server
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient();
                client.Connect(textBoxServerIp.Text, Convert.ToInt32(textBoxPort.Text));
                stream = client.GetStream();
                isConnected = true;
                MessageBox.Show("Connection established, you may send messages now!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Connection failed:" + ex.Message);
            }
        }

        // Core logic for message transmission
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!isConnected)
            {
                MessageBox.Show("Please connect to server first!");
                return;
            }
            string content = textBoxSend.Text.Trim();
            if (string.IsNullOrEmpty(content))
                return;

            // Detect exit command
            if (content == "Exit")
            {
                byte[] exitData = Encoding.Unicode.GetBytes(content);
                stream.Write(exitData, 0, exitData.Length);

                // Release allocated resources
                stream.Close();
                client.Close();
                isConnected = false;
                MessageBox.Show("Connection closed");
                return;
            }

            // Send regular custom payload
            byte[] data = Encoding.Unicode.GetBytes(content);
            stream.Write(data, 0, data.Length);
            textBoxSend.Clear();
        }
    }
}Code language: C# (cs)
static void Main(string[] args)
{
    TcpClient client = new TcpClient();
    client.Connect("127.0.0.1", 8899);
    NetworkStream stream = client.GetStream();
    while (true)
    {
        Console.Write("Type your message:");
        string msg = Console.ReadLine();
        byte[] buf = Encoding.Unicode.GetBytes(msg);
        stream.Write(buf,0,buf.Length);
        if (msg == "Exit")
        {
            stream.Close();
            client.Close();
            break;
        }
    }
}Code language: JavaScript (javascript)

If you want, I can refactor the whole codebase into pure‑async async/await pattern, fully removing child threads together with the bad practice of disabling cross‑thread validation.

Continuous message sending on client side

Leave a Reply

Your email address will not be published. Required fields are marked *