Files
2026-04-30 11:34:41 +08:00

99 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace SamplePre.Communication.Communication
{
public class SocketClient
{
// 服务端 IP 和端口(和你服务端一致)
private const string ServerIp = "127.0.0.1";
private const int ServerPort = 8888;
private Socket _clientSocket;
public Action<string> ReceiveMsgAction;
//static async Task Main(string[] args)
//{
// var client = new SocketClient();
// await client.StartClientAsync();
//}
/// <summary>
/// 启动客户端
/// </summary>
public async Task StartClientAsync()
{
try
{
// 创建客户端 Socket
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ReceiveMsgAction?.Invoke("正在连接服务端...");
// 连接服务端
await _clientSocket.ConnectAsync(IPAddress.Parse(ServerIp), ServerPort);
ReceiveMsgAction?.Invoke("✅ 连接服务端成功!");
// 启动接收消息任务(后台异步监听)
_ = Task.Run(ReceiveMsgAsync);
}
catch (Exception ex)
{
ReceiveMsgAction?.Invoke($"连接失败:{ex.Message}");
}
}
public void CloseConnect()
{
_clientSocket.Close();
ReceiveMsgAction?.Invoke("客户端已断开");
}
/// <summary>
/// 发送消息
/// </summary>
public async Task SendMsgAsync(string msg)
{
if (string.IsNullOrEmpty(msg)) return;
byte[] data = Encoding.UTF8.GetBytes(msg);
await _clientSocket.SendAsync(data, SocketFlags.None);
}
/// <summary>
/// 接收服务端消息
/// </summary>
private async Task ReceiveMsgAsync()
{
byte[] buffer = new byte[1024];
while (true)
{
try
{
int len = await _clientSocket.ReceiveAsync(buffer, SocketFlags.None);
if (len == 0) break;
string recMsg = Encoding.UTF8.GetString(buffer, 0, len);
//回调函数
ReceiveMsgAction?.Invoke($"\n📩 服务端回复:{recMsg}");
}
catch
{
break;
}
}
}
}
}