zl程序教程

您现在的位置是:首页 >  云平台

当前栏目

编写TCP客户端应用程序

2023-09-11 14:16:46 时间

编写C#代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TCPClientApplicationProgram
{
    public partial class Form1 : Form
    {
        Socket clientSocket;
        Thread clientThread;

        public Form1()
        {
            InitializeComponent();

            //对跨线程的非法错误不检查
            Control.CheckForIllegalCrossThreadCalls = false;

            this.IP_textBox1.Text = "127.0.0.1";

            this.Port_textBox2.Text = "6001";
        }

        private void Send_button_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];

            //对输入信息进行编码并放到一个字节数组
            data = Encoding.ASCII.GetBytes(this.Content_textBox3.Text);

            //向服务器发送信息
            clientSocket.Send(data, data.Length, SocketFlags.None);
        }

        private void ConnectSever_button1_Click(object sender, EventArgs e)
        {
            if(this.IP_textBox1.Text=="")
            {
                MessageBox.Show("请输入IP!");
                return;
            }

            //开启一个子线程,连接到服务器
            clientThread = new Thread(new ThreadStart(ConnectToServer));
            clientThread.Start();
        }

        private void ConnectToServer()
        {
            byte[] data = new byte[1024];

            //网络地址和服务端口的组合称为端点,IPEndPoint类表示这个端口
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(this.IP_textBox1.Text), int.Parse(this.Port_textBox2.Text));

            //初始化Socket
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //将套接字与远程服务器地址相连
            try
            {
                //连接到服务器
                clientSocket.Connect(ipep);
            }
            catch(SocketException ex)
            {
                MessageBox.Show("connect error:" + ex.Message);
            }
        }
    }
}

 WindowsForm截图如下:

需要打开上一节VisionPro作业:编写二维码识别Quickbuild工程,最终运行效果如下:

 参考:

蔚来教育企业店