C# realizes TCP communication --- Windows form application using VS

1. UI interface settings

Insert picture description here
1. Three button controls, using the Click() event.
2. Three GroupBox controls, which can display characters in a certain area, such as server.
3. Two RichTextBox controls are used to display input and received data.
4. A Timer control, used to receive data processing

Second, the server implementation code

1. Related variables

//定义的类内变量
        private TcpListener Listener;
        private Socket SocketClient;
        private NetworkStream NetStream;
        private StreamReader ServerReader;
        private StreamWriter ServerWriter;
        private Thread Thread;

2. Core code

2.1 running thread function

public void TCPListener()
{
   //在这里填入你的ip地址
   this.Listener = new TcpListener(IPAddress.Parse("192.168.31.62"), 8000);
   Listener.Start();
   button1.Enabled = false;
   this.Text = "服务器正在运行中。。。";
   while (true)
   {
       try
       {
           SocketClient = Listener.AcceptSocket();         //等待客户端的socket
           NetStream = new NetworkStream(SocketClient);    //有客户端连接成功后,创建网络流
           ServerReader = new StreamReader(NetStream);     //读数据
           ServerWriter = new StreamWriter(NetStream);     //写数据
           
       }
       catch
       {

       }
   }
}

 This function is the execution function of the thread, which constantly waits for the socket connection of the client and receives data.
 This function assigns a new thread after the button is pressed, and the button is locked after pressing, that is, the server only needs to run one thread, and the client can have multiple threads running to connect to the server.

2.2 Receive function

public void GetMessage()
{
     //网络流不为空并且有可用数据
     if (NetStream != null && NetStream.DataAvailable)
     {
         richTextBox1.AppendText(DateTime.Now.ToString());//显示时间
         richTextBox1.AppendText("  客户端说:\n");
         richTextBox1.AppendText(ServerReader.ReadLine() + "\n");
         //设置下拉框
         richTextBox1.SelectionStart = richTextBox1.Text.Length;
         richTextBox1.Focus();
         richTextBox2.Focus();
     }
 }

 This function runs in the interrupt trigger function of the timer, and prints it in the receive box control when there is data in the network stream.

3. Key trigger function

3.1 Connect to the server

private void button1_Click(object sender, EventArgs e)
{
    this.Thread = new Thread(new ThreadStart(TCPListener));
    this.Thread.Start();
}

 Start the thread, set the thread running function to TCPListener(), the specific function is in 2.1

3.2 Send data

private void button3_Click(object sender, EventArgs e)
{
    try
    {
        if (richTextBox2.Text.Trim() != "")
        {
            //信息写入流
            ServerWriter.WriteLine(richTextBox2.Text);
            ServerWriter.Flush();
            //显示在文本框上。
            richTextBox1.AppendText(DateTime.Now.ToString());
            richTextBox1.AppendText("  服务器说:\n");
            richTextBox1.AppendText(richTextBox2.Text + "\n");
            richTextBox2.Clear();
            //滚动条
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.Focus();
            richTextBox2.Focus();
        }
        else
        {
            MessageBox.Show("信息不能为空!", "服务器消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            richTextBox2.Focus();
            return;
        }
    }
    catch
    {
        MessageBox.Show("客户端连接失败……", "服务器消息", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
}

 When the user clicks send, it will be sent to the client according to the data entered in the text box and displayed in the message receiving box.

3.3 Clear data

private void button2_Click(object sender, EventArgs e)
{
     richTextBox1.Clear();
 }

 Clear the data in the receiving box.

4. Other modules

4.1 Constructor

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

4.2 Form related events

private void Form1_Load(object sender, EventArgs e)
 {
     this.richTextBox1.ReadOnly = true;  //只读
     this.timer1.Enabled = true;         //定时器使能
 }

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     DialogResult dr = MessageBox.Show("关闭服务器将无法接收到来自客户端的数据,你确定要关闭吗?", "服务器信息", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
     if (dr == DialogResult.Yes)
     {
         Listener.Stop();
         this.Thread.Abort();
         e.Cancel = false;
     }
     else
     {
         e.Cancel = true;
     }
 }

 In the event function of the form, you can do some initialization operations, and close the socket and thread when closing the form, otherwise an abnormal error will occur.
For details, please check one of my blogs

4.3 Timer events

private void timer1_Tick(object sender, EventArgs e)
{
     //接收数据,处理数据
     GetMessage();
 }

 Call the data receiving function GetMessage() to continuously process the received data.

Third, the client implementation code

1. Explain

 The client code implementation is similar to the server, but you need to select the IP and port to connect to the server.
** PS: The server and client code run under the same LAN, that is, use the same router or hotspot. Use ipconfig to view the IP in the console and fill in the relevant location.

2. Core code

public void GetConn()
{
    CheckForIllegalCrossThreadCalls = false;
    while (true)
    {
        try
        {
            TcpClient = new TcpClient(textBox1.Text.Trim(), Convert.ToInt32(textBox2.Text.Trim()));
            Stream = TcpClient.GetStream();
            //创建读写流
            ClientReader = new StreamReader(Stream);
            ClientWriter = new StreamWriter(Stream);
            textBox1.Enabled = false;
            button1.Enabled = false;
            this.Text = "客户端   " + "与" + textBox1.Text.Trim() + "连接成功!";
            return;
        }
        catch (Exception e)
        {
            textBox1.Enabled = true;
            button1.Enabled = true;
            MessageBox.Show(e.ToString());
            return;
            //MessageBox.Show("连接失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

 This function is a thread execution function of the client, using the TcpClient class.
 The rest is roughly the same as the server. After understanding the server, writing the client is actually in the process of finding out the picture.
 If you still don’t understand, you can click here . Here are the resources I uploaded and the complete project.

I wish you all a happy learning!

Guess you like

Origin blog.csdn.net/aruewds/article/details/109262823