using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MakeAppointment
{
public partial class Form2 : Form
{
private ClientWebSocket _clientWebSocket;
private CancellationTokenSource _cancellationTokenSource;
public Form2(){InitializeComponent();this.FormClosing += WebSocketClientForm_FormClosing;}private async void WebSocketClientForm_FormClosing(object sender, FormClosingEventArgs e){if (_clientWebSocket != null && _clientWebSocket.State == WebSocketState.Open){await _clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client closing", CancellationToken.None);}}private async void ConnectButton_Click(object sender, EventArgs e){try{_clientWebSocket = new ClientWebSocket();_cancellationTokenSource = new CancellationTokenSource();await _clientWebSocket.ConnectAsync(new Uri("ws://localhost:8080"), _cancellationTokenSource.Token);LogMessage("已连接到 WebSocket 服务端。");// 开始接收消息_ = ReceiveMessagesAsync();}catch (Exception ex){LogMessage($"连接服务端时出错: {ex.Message}");}}private async void SendButton_Click(object sender, EventArgs e){if (_clientWebSocket != null && _clientWebSocket.State == WebSocketState.Open){var message = MessageTextBox.Text;if (!string.IsNullOrEmpty(message)){var buffer = Encoding.UTF8.GetBytes(message);await _clientWebSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, _cancellationTokenSource.Token);LogMessage($"已发送消息: {message}");}}}private async Task ReceiveMessagesAsync(){var buffer = new byte[1024];while (_clientWebSocket.State == WebSocketState.Open){var result = await _clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), _cancellationTokenSource.Token);if (result.MessageType == WebSocketMessageType.Text){var message = Encoding.UTF8.GetString(buffer, 0, result.Count);LogMessage($"收到服务端消息: {message}");}}}private void LogMessage(string message){if (this.InvokeRequired){this.Invoke(new Action(() =>{LogTextBox.AppendText($"{DateTime.Now}: {message}{Environment.NewLine}");}));}else{LogTextBox.AppendText($"{DateTime.Now}: {message}{Environment.NewLine}");}}}
}