通过NuGet来安装SuperSocket客户端,SuperSocket.ClientEngine
实现代码如下:
public partial class MainPage : Page { SuperSocket.ClientEngine.AsyncTcpSession client = null; public MainPage() { InitializeComponent(); DataContext = ViewModel.MainWindowViewModel.CreateInstance(); client = new SuperSocket.ClientEngine.AsyncTcpSession(); //连接到服务器事件 client.Connected += Client_Connected; //连接断开事件 client.Closed += Client_Closed; //发生错误的处理 client.Error += Client_Error; //收到服务器数据事件:注意 接收消息每次接收4096字节【4KB】, //如果发送的消息大于4096字节,将分多段发送,也就是触发多次DataReceived事件 client.DataReceived += DataReceived; } private void Client_Connected(object sender, EventArgs e) { if (client.IsConnected) { Console.Write("连接成功"); } } private void Client_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e) { Console.Write($"错误事件触发:{e.Exception.Message}"); } private void Client_Closed(object sender, EventArgs e) { Console.Write("连接断开"); } private void DataReceived(object sender, SuperSocket.ClientEngine.DataEventArgs e) { Console.Write($"接收到消息【length:{e.Length}】:{Encoding.Default.GetString(e.Data, e.Offset, e.Length)}"); } /// <summary> /// 发送消息 /// </summary> /// <param name="message"></param> private void Send(string message) { if (!client.IsConnected) { Console.Write("尚未连接到服务端,无法发送..."); return; } byte[] data = Encoding.Default.GetBytes(message); client.Send(data, 0, data.Length); } }
标签:Console,SuperSocket,ClientEngine,client,Write,Client,客户端 From: https://www.cnblogs.com/microsoft-zh/p/18295757