You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
namespace SocketExample
{
/// <summary>
/// ClientWindow.xaml 的交互逻辑
/// </summary>
public partial class ClientWindow : Window
{
IPAddress ip;
int port;
TcpClient client;
NetworkStream stream;
Thread thread;
public ClientWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
ip = IPAddress.Parse(IPtextbox.Text);
port = int.Parse(Porttextbox.Text);
client = new TcpClient();
// 开始监听
client.Connect(ip, port);
thread = new Thread(Recive);
thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
InfoTextBlock_Client.Text += $"处理请求时出错: {ex.Message}\n";
});
}
}
private void Button_Click_Send(object sender, RoutedEventArgs e)
{
try
{
string message = MessageTextBox_Client.Text;
// 如果发送"exit"则退出
if (message.ToLower() == "exit")
{
stream.Close();
client.Close();
thread.Abort();
}
else
{
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
}
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
InfoTextBlock_Client.Text += $"处理请求时出错: {ex.Message}\n";
});
}
}
void Recive()
{
stream = client.GetStream();
while (true)
{
// 处理客户端请求
try
{
// 接收响应
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Dispatcher.Invoke(() =>
{
this.InfoTextBlock_Client.Text += $"服务器响应: {response}\n";
});
}
catch (Exception ex)
{
Dispatcher.Invoke(() =>
{
InfoTextBlock_Client.Text += $"处理请求时出错: {ex.Message}\n";
});
}
}
// 关闭连接
}
}
}