编写C#代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 using System.Net;
11 using System.Net.Sockets;
12 using System.Threading;
13  
14 namespace TCPClientApplicationProgram
15 {
16     public partial class Form1 : Form
17     {
18         Socket clientSocket;
19         Thread clientThread;
20  
21         public Form1()
22         {
23             InitializeComponent();
24  
25             //对跨线程的非法错误不检查
26             Control.CheckForIllegalCrossThreadCalls = false;
27  
28             this.IP_textBox1.Text = "127.0.0.1";
29  
30             this.Port_textBox2.Text = "6001";
31         }
32  
33         private void Send_button_Click(object sender, EventArgs e)
34         {
35             byte[] data = new byte[1024];
36  
37             //对输入信息进行编码并放到一个字节数组
38             data = Encoding.ASCII.GetBytes(this.Content_textBox3.Text);
39  
40             //向服务器发送信息
41             clientSocket.Send(data, data.Length, SocketFlags.None);
42         }
43  
44         private void ConnectSever_button1_Click(object sender, EventArgs e)
45         {
46             if(this.IP_textBox1.Text=="")
47             {
48                 MessageBox.Show("请输入IP!");
49                 return;
50             }
51  
52             //开启一个子线程,连接到服务器
53             clientThread = new Thread(new ThreadStart(ConnectToServer));
54             clientThread.Start();
55         }
56  
57         private void ConnectToServer()
58         {
59             byte[] data = new byte[1024];
60  
61             //网络地址和服务端口的组合称为端点,IPEndPoint类表示这个端口
62             IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(this.IP_textBox1.Text), int.Parse(this.Port_textBox2.Text));
63  
64             //初始化Socket
65             clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
66  
67             //将套接字与远程服务器地址相连
68             try
69             {
70                 //连接到服务器
71                 clientSocket.Connect(ipep);
72             }
73             catch(SocketException ex)
74             {
75                 MessageBox.Show("connect error:" + ex.Message);
76             }
77         }
78     }
79 }

WindowsForm截图如下:

C# 编写TCP客户端应用程序_ipad

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

C# 编写TCP客户端应用程序_.net_02