使用SuperSockett.ClientEngine可以进行客户端通信,演示AsyncTcpSession进行连接、发送、接收等操作。
新建Windows窗体应用程序,使用.net framework 4.5,添加对SuperSockett.ClientEngine.dll的引用。
一、在项目上新建windows窗体Form2窗体设计如图:
二、编写Form2.cs相关源程序(忽略设计器自动生成的代码),注意:
注意:Client_Connected事件触发后,才会将client.IsConnected设置为true。因Connect(endPoint)方法是异步的,连接成功后,才置IsConnected=true,然后触发Client_Connected连接成功事件
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SuperSocketClientDemo
{
public partial class Form2 : Form
{
SuperSocket.ClientEngine.AsyncTcpSession client = new SuperSocket.ClientEngine.AsyncTcpSession();
public Form2()
{
InitializeComponent();
//连接到服务器事件
client.Connected += Client_Connected;
//连接断开事件
client.Closed += Client_Closed;
//发生错误的处理
client.Error += Client_Error;
//收到服务器数据事件:注意 接收消息每次接收4096字节【4KB】,如果发送的消息大于4096字节,将分多段发送,也就是触发多次DataReceived事件
client.DataReceived += Client_DataReceived;
}
private void Client_DataReceived(object sender, SuperSocket.ClientEngine.DataEventArgs e)
{
string display = string.Format("接收到消息【length:{0}】:{1}", e.Length, Encoding.Default.GetString(e.Data, e.Offset, e.Length));
DisplayInfo(display);
}
private void Client_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
{
DisplayInfo("错误事件触发:" + e.Exception.Message);
}
private void Client_Closed(object sender, EventArgs e)
{
DisplayInfo("连接断开");
}
private void Client_Connected(object sender, EventArgs e)
{
DisplayInfo("连接成功");
if (client.IsConnected)
{
Send("Hello AsyncTcpSession");
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
client.Connect(new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text)));
}
/// <summary>
/// 显示富文本框的消息
/// </summary>
/// <param name="message"></param>
private void DisplayInfo(string message)
{
this.BeginInvoke(new Action(() =>
{
if (richTextBox1.TextLength >= 10240)
{
richTextBox1.Clear();
}
richTextBox1.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} --> {message}\n");
}));
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="message"></param>
private void Send(string message)
{
if (!client.IsConnected)
{
DisplayInfo("尚未连接到服务端,无法发送...");
return;
}
byte[] data = Encoding.Default.GetBytes(message);
client.Send(data, 0, data.Length);
}
private void btnSend_Click(object sender, EventArgs e)
{
Send(rtxtSend.Text);
}
}
}
三、程序运行截图如下【每次最多接收4096字节,如果服务端一次发送10000字节,则OnReceived事件将会触发三次,分段接收】: