cross socket tcp客户端开发
cross socket tcp客户端开发
uses Net.SocketAPI, Net.CrossSocket.Base, Net.CrossSocket
FCrossTcp: ICrossSocket;
ICrossSocket说明
CROSS SOCKET的TCP服务端和客户端都是使用ICrossSocket。
接收消息事件
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对象
procedure TForm1.FormCreate(Sender: TObject); begin FCrossTcp := TCrossSocket.Create(1); FCrossTcp.OnReceived := OnReceived; end;
连接TCP服务端
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;
向服务端发送请求
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;
断开连接
procedure TForm1.DisConnect; begin FCrossTcp.DisconnectAll; end;
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/11359526.html