WPF控件编程实践TCP客户端示例代码

northestknight 9 0 zip 2023-03-12 07:03:49

using System;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Controls;

namespace WPF控件编程实践
{
    public partial class MainWindow : Window
    {
        private TcpClient tcpClient;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                tcpClient = new TcpClient(AddressTextBox.Text, int.Parse(PortTextBox.Text));
                StatusLabel.Content = "已连接";
            }
            catch (Exception ex)
            {
                StatusLabel.Content = "连接失败:" + ex.Message;
            }
        }

        private void SendButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(MessageTextBox.Text);
                tcpClient.GetStream().Write(buffer, 0, buffer.Length);
                StatusLabel.Content = "发送成功";
            }
            catch (Exception ex)
            {
                StatusLabel.Content = "发送失败:" + ex.Message;
            }
        }

        private void DisconnectButton_Click(object sender, RoutedEventArgs e)
        {
            tcpClient.Close();
            StatusLabel.Content = "已断开";
        }
    }
}

用户评论
请输入评论内容
评分:
暂无评论