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 = "已断开";
        }
    }
}