@@ -74,4 +74,42 @@ public static void SetDataPackageAdapter(this ITcpSocketClient client, IDataPack
7474 // 设置 DataPackageAdapter 的回调函数
7575 adapter . ReceivedCallBack = buffer => callback ( buffer ) ;
7676 }
77+
78+ /// <summary>
79+ /// Configures the specified <see cref="ITcpSocketClient"/> to use a custom data package adapter and a callback
80+ /// function for processing received data.
81+ /// </summary>
82+ /// <remarks>This method sets up the <paramref name="client"/> to use the provided <paramref
83+ /// name="adapter"/> for handling incoming data. The adapter processes the raw data received by the client and
84+ /// attempts to convert it into an instance of <typeparamref name="TEntity"/>. If the conversion is successful, the
85+ /// <paramref name="callback"/> is invoked with the converted entity; otherwise, it is invoked with <see
86+ /// langword="null"/>.</remarks>
87+ /// <typeparam name="TEntity">The type of the entity that the data package adapter will attempt to convert the received data into.</typeparam>
88+ /// <param name="client">The <see cref="ITcpSocketClient"/> instance to configure.</param>
89+ /// <param name="adapter">The <see cref="IDataPackageAdapter"/> instance responsible for handling and processing incoming data.</param>
90+ /// <param name="callback">A callback function to be invoked with the processed data of type <typeparamref name="TEntity"/>. The callback
91+ /// receives <see langword="null"/> if the data cannot be converted to <typeparamref name="TEntity"/>.</param>
92+ public static void SetDataPackageAdapter < TEntity > ( this ITcpSocketClient client , IDataPackageAdapter adapter , Func < TEntity ? , Task > callback )
93+ {
94+ // 设置 ITcpSocketClient 的回调函数
95+ client . ReceivedCallBack = async buffer =>
96+ {
97+ // 将接收到的数据传递给 DataPackageAdapter 进行数据处理合规数据触发 ReceivedCallBack 回调
98+ await adapter . HandlerAsync ( buffer ) ;
99+ } ;
100+
101+ // 设置 DataPackageAdapter 的回调函数
102+ adapter . ReceivedCallBack = async buffer =>
103+ {
104+ TEntity ? ret = default ;
105+ if ( adapter . TryConvertTo ( buffer , out var t ) )
106+ {
107+ if ( t is TEntity entity )
108+ {
109+ ret = entity ;
110+ }
111+ }
112+ await callback ( ret ) ;
113+ } ;
114+ }
77115}
0 commit comments