TCP公共库
# 敢为公共库
敢为公共库中TCP公共库的介绍
# 通讯组件 IoTCenter.Extensions.Net
通用socket通信库(.net standard) ,支持tcp协议服务端
# 安装教程
通过Nuget(https://nuget.ganweicloud.com)安装
Install-Package IoTCenter.Extensions.Net
# 接口定义
接口定义代码
public interface IServer : IDisposable
{
bool Active { get; } //服务是否活动
EndPoint LocalEndPoint { get; } //本地监听终结点
void Start(); //开启服务
void Stop(); //关闭服务
bool Send(SocketToken token, byte[] buffer); //同步发送消息,SocketToken为通讯会话对象
bool SendAsync(SocketToken token, byte[] buffer); //异步发送消息,SocketToken为通讯会话对象
event AcceptedHandler OnAccepted; //连接事件
event ClosedHandler OnClosed; //连接关闭事件
event PactetHandler OnReceived; //接收数据事件
event PactetHandler OnSent; //发送数据事件
event MessageHandler OnDebug; //调试信息事件
event MessageHandler OnError; //异常信息事件
}
# 使用示例
# tcp服务端
tcp服务端
class Program
{
static void Main(string[] args)
{
IocpServer server = new IocpServer(endPoint);
server.OnAccepted += Server_OnAccepted;
server.OnClosed += Server_OnClosed;
server.OnReceived += Server_OnReceived;
server.OnSent += Server_OnSent;
server.OnDebug += Server_OnDebug;
server.OnError += Server_OnError;
server.Start();
}
private static void Server_OnError(string text, Exception exception = null)
{
logger.Error(text, exception);
}
private static void Server_OnDebug(string text, Exception exception = null)
{
logger.Debug(text);
}
private static void Server_OnSent(SocketToken userToken, byte[] buffer)
{
logger.Debug($"send data {userToken.Client.RemoteEndPoint}:" + string.Join(" ", buffer.Select(r => r.ToString("X2"))));
}
private static void Server_OnReceived(SocketToken userToken, byte[] buffer)
{
logger.Debug($"receive data {userToken.Client.RemoteEndPoint}:" + string.Join(" ", buffer.Select(r => r.ToString("X2"))));
}
private static void Server_OnClosed(EndPoint endPoint)
{
logger.Info($"{endPoint} closed");
}
private static void Server_OnAccepted(SocketToken userToken, EndPoint endPoint)
{
logger.Info($"{endPoint} accepted");
var buff = Encoding.ASCII.GetBytes("hello");
userToken.SendAsync(buff);//userToken.Send(buff);
}
}
上次更新: 2023/7/21 09:43:31