WinForm之TCP客户端通讯

目录

一 设计界面

二 后台代码


一 设计界面

二 后台代码

using System.Net.Sockets;
using System.Text;

namespace TCP网络客户端通讯
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        TcpClient tcpClient = new TcpClient();

        private void connect_Click(object sender, EventArgs e)
        {
            if (!tcpClient.Connected)
            {
                tcpClient.Connect(IP.Text, int.Parse(PORT.Text));

                //开启线程一直读取数据
                Task.Run(() =>
                {
                    while (true)
                    {
                        NetworkStream networkStream = tcpClient.GetStream();
                        if (networkStream != null)
                        {
                            byte[] datas = new byte[1024];
                            networkStream.Read(datas, 0, datas.Length);
                            this.BeginInvoke(new Action(() =>
                            {
                                log.Text = Encoding.UTF8.GetString(datas);
                            }));
                        }
                    }
                });
            }
        }

        private void send_Click(object sender, EventArgs e)
        {
            NetworkStream networkStream = tcpClient.GetStream();
            if (networkStream != null)
            {
                byte[] datas = Encoding.UTF8.GetBytes(log.Text);
                networkStream.Write(datas, 0, datas.Length);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            IP.Text = "127.0.0.1";
            PORT.Text = "8899";
        }
    }
}

设计器自动生成代码:

namespace TCP网络客户端通讯
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            label1 = new Label();
            label2 = new Label();
            IP = new TextBox();
            PORT = new TextBox();
            connect = new Button();
            log = new RichTextBox();
            send = new Button();
            SuspendLayout();
            // 
            // label1
            // 
            label1.AutoSize = true;
            label1.Location = new Point(32, 52);
            label1.Name = "label1";
            label1.Size = new Size(22, 20);
            label1.TabIndex = 0;
            label1.Text = "IP";
            // 
            // label2
            // 
            label2.AutoSize = true;
            label2.Location = new Point(32, 113);
            label2.Name = "label2";
            label2.Size = new Size(39, 20);
            label2.TabIndex = 1;
            label2.Text = "端口";
            // 
            // IP
            // 
            IP.Location = new Point(103, 52);
            IP.Name = "IP";
            IP.Size = new Size(125, 27);
            IP.TabIndex = 2;
            // 
            // PORT
            // 
            PORT.Location = new Point(103, 110);
            PORT.Name = "PORT";
            PORT.Size = new Size(125, 27);
            PORT.TabIndex = 3;
            // 
            // connect
            // 
            connect.Location = new Point(32, 185);
            connect.Name = "connect";
            connect.Size = new Size(196, 29);
            connect.TabIndex = 4;
            connect.Text = "连接";
            connect.UseVisualStyleBackColor = true;
            connect.Click += connect_Click;
            // 
            // log
            // 
            log.Location = new Point(32, 258);
            log.Name = "log";
            log.Size = new Size(196, 134);
            log.TabIndex = 5;
            log.Text = "";
            // 
            // send
            // 
            send.Location = new Point(32, 416);
            send.Name = "send";
            send.Size = new Size(196, 29);
            send.TabIndex = 6;
            send.Text = "发送数据";
            send.UseVisualStyleBackColor = true;
            send.Click += send_Click;
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(9F, 20F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(391, 497);
            Controls.Add(send);
            Controls.Add(log);
            Controls.Add(connect);
            Controls.Add(PORT);
            Controls.Add(IP);
            Controls.Add(label2);
            Controls.Add(label1);
            MaximizeBox = false;
            Name = "Form1";
            Text = "TCP客户端通讯";
            Load += Form1_Load;
            ResumeLayout(false);
            PerformLayout();
        }

        #endregion

        private Label label1;
        private Label label2;
        private TextBox IP;
        private TextBox PORT;
        private Button connect;
        private RichTextBox log;
        private Button send;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 WinForms TCP/IP 客户端的代码示例: ```csharp using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Windows.Forms; namespace TCPClientExample { public partial class MainForm : Form { private TcpClient client; private NetworkStream stream; private byte[] buffer; public MainForm() { InitializeComponent(); } private void connectButton_Click(object sender, EventArgs e) { try { // 创建 TCP 客户端对象并连接到指定的 IP 地址和端口号 client = new TcpClient(); client.Connect(IPAddress.Parse(ipTextBox.Text), int.Parse(portTextBox.Text)); // 获取网络流 stream = client.GetStream(); buffer = new byte[client.ReceiveBufferSize]; // 连接成功后禁用连接按钮 connectButton.Enabled = false; // 开始异步读取数据 stream.BeginRead(buffer, 0, buffer.Length, ReadCallback, null); } catch (Exception ex) { MessageBox.Show("连接失败:" + ex.Message); } } private void sendButton_Click(object sender, EventArgs e) { try { // 将消息转换为字节数组 byte[] data = Encoding.UTF8.GetBytes(messageTextBox.Text); // 发送消息到服务器 stream.Write(data, 0, data.Length); } catch (Exception ex) { MessageBox.Show("发送失败:" + ex.Message); } } private void ReadCallback(IAsyncResult ar) { try { // 结束异步读取操作并获取接收到的字节数 int bytesRead = stream.EndRead(ar); if (bytesRead > 0) { // 将接收到的字节数组转换为字符串 string message = Encoding.UTF8.GetString(buffer, 0, bytesRead); // 在消息框中显示接收到的消息 Invoke(new Action(() => { messagesTextBox.AppendText(message + Environment.NewLine); })); // 继续异步读取数据 stream.BeginRead(buffer, 0, buffer.Length, ReadCallback, null); } } catch (Exception ex) { MessageBox.Show("读取失败:" + ex.Message); } } } } ``` 这个示例中,我们创建了一个 `MainForm` 类来实现我们的客户端界面。界面上有一个文本框用于输入服务器IP 地址,一个文本框用于输入服务器的端口号,一个文本框用于输入要发送的消息,一个按钮用于连接到服务器,一个按钮用于发送消息,以及一个文本框用于显示接收到的消息。 在 `connectButton_Click` 事件处理程序中,我们创建了一个 `TcpClient` 对象,并使用 `Connect` 方法连接到指定的 IP 地址和端口号。然后,我们获取网络流,并设置一个接收缓冲区来存储接收到的数据。最后,我们使用 `BeginRead` 方法开始异步读取数据。 在 `sendButton_Click` 事件处理程序中,我们将要发送的消息转换为字节数组,并使用网络流的 `Write` 方法将其发送到服务器。 在 `ReadCallback` 方法中,我们结束异步读取操作,并获取接收到的字节数。如果接收到的字节数大于零,我们将接收到的字节数组转换为字符串,并在消息框中显示出来。然后,我们使用 `BeginRead` 方法继续异步读取数据。 请注意,这只是一个简单的示例,没有处理错误、关闭连接等方面的逻辑。在实际应用中,您可能需要添加更多的错误处理和逻辑来实现更完整的客户端功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值