cross socket tcp客户端开发
cross socket tcp客户端开发
uses Net.SocketAPI, Net.CrossSocket.Base, Net.CrossSocket
FCrossTcp: ICrossSocket;
ICrossSocket说明
CROSS SOCKET的TCP服务端和客户端都是使用ICrossSocket。
接收消息事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | procedure TForm1.OnReceived(Sender: TObject; AConnection: ICrossConnection; ABuf: Pointer; ALen: Integer); begin TThread.Queue(nil, procedure begin var ms: tstream := TMemoryStream.Create; ms.Size := ALen; ms.Write(ABuf^, ALen); ms.Position := 0; var ms2: tstream := TMemoryStream.Create; tzip.UnZipStream(ms, ms2); //unzip ms.Free; ms2.Position := 0; var pack: tmsgpack := TMsgPack.Create; pack.DecodeFromStream(ms2); case pack.Force( 'cmd' ).AsInteger of cmd_query: begin form1.ClientDataSet1.Data := pack.Force( 'dataset1' ).AsVariant; form1.ClientDataSet2.Data := pack.Force( 'dataset2' ).AsVariant; end; end; pack.Free; end); end; |
创建TCP对象
1 2 3 4 5 | procedure TForm1.FormCreate(Sender: TObject); begin FCrossTcp := TCrossSocket.Create(1); FCrossTcp.OnReceived := OnReceived; end; |
连接TCP服务端
1 2 3 4 5 6 7 8 9 10 11 12 13 | procedure TForm1.Connect(ip: string ; port: Word); begin FCrossTcp.Connect(ip, port, procedure(AConnection: ICrossConnection; ASuccess: Boolean) begin TThread.Queue(nil, procedure begin if ASuccess then form1.Button1.Enabled := false ; end) end); end; |
向服务端发送请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | procedure TForm1.execRemoteFunc(pack: TMsgPack); begin var Conns: TArray<ICrossConnection> := FCrossTcp.LockConnections.Values.ToArray; var Conn: ICrossConnection := Conns[0]; var ms: TStream := TMemoryStream.Create; pack.EncodeToStream(ms); pack.Free; ms.Position := 0; Conn.SendStream(ms, procedure(AConnection: ICrossConnection; ASuccess: Boolean) begin ms.Free; end); FCrossTcp.UnlockConnections; end; |
断开连接
1 2 3 4 | procedure TForm1.DisConnect; begin FCrossTcp.DisconnectAll; end; |
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/11359526.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?