客户端:
定义
private AsyncTcpSession client;
初始化
client = new AsyncTcpSession(); client.Connected += ClientOnConnected; client.Closed += ClientOnClosed; client.DataReceived += ClientOnDataReceived; ThreadPool.QueueUserWorkItem(ConnectServer_Loop);
事件
private void ClientOnDataReceived(object sender, DataEventArgs e) { var dat = Encoding.Default.GetString(e.Data.Take(e.Length).ToArray());
//使用有效数据长度截取数组,可消除数据中的多余空字符 textBox1.AppendText($"收到数据:{dat}"); } private void ClientOnClosed(object sender, EventArgs e) { textBox1.AppendText($"服务器连接关闭{Environment.NewLine}"); } private void ClientOnConnected(object sender, EventArgs e) { textBox1.AppendText($"已连接服务器{Environment.NewLine}"); }
持续线程
private void ConnectServer_Loop(object state) { if (ConnectServer_Loop_workState) return; ConnectServer_Loop_workState = true; while (ConnectServer_Loop_workState) { Thread.Sleep(1000); if (!client.IsConnected) { try { client.Connect(new IPEndPoint(IPAddress.Parse("192.168.15.2"), 57900)); } catch {} } } ConnectServer_Loop_workState = false; } private bool ConnectServer_Loop_workState; private void ConnectServer_Loop_Stop() => ConnectServer_Loop_workState = false;
此外,客户端发送数据后必须在结尾添加回车换行标志,否则服务端不能触发接收消息事件