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,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步