cross socket tcp客户端开发
Posted hnxxcxg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
以上是关于cross socket tcp客户端开发的主要内容,如果未能解决你的问题,请参考以下文章
W5500开发笔记 | 02 - 使用W5500 Socket API 建立TCP服务端TCP客户端
7-网络芯片CH395Q学习开发-模块使用Socket0-5作为6路TCP客户端和电脑上位机TCP客户端局域网通信(Socket缓存区配置)