zoukankan      html  css  js  c++  java
  • 把 TBytes 转换为十六进制字符串

    function BytestoHexString(ABytes: TBytes; len: Integer): AnsiString;
    begin
      SetLength(Result, len*2);
      BinToHex(@ABytes[0], PAnsiChar(Result), len);
    end;

    例子:

    客户端:

        IdTCPClient1: TIdTCPClient;
        Button1: TButton;
        mmo1: TMemo;

    procedure TForm4.Button1Click(Sender: TObject);
    var
      b:TBytes;
      Len:Integer;
      str:string;
    begin
      IdTCPClient1.Host:= '127.0.0.1';
      IdTCPClient1.Port:= 8090;
      if not IdTCPClient1.Connected then
        IdTCPClient1.Connect;
      if IdTCPClient1.Connected then
      begin
        IdTCPClient1.IOHandler.WriteLn('QUERYDATA');
        mmo1.Lines.Add('向服务器发送:QUERYDATA') ;
        try
          IdTCPClient1.IOHandler.CheckForDataOnSource(250);//等待
          Len:= IdTCPClient1.IOHandler.InputBuffer.Size;
          IdTCPClient1.IOHandler.ReadBytes(b,len,false);
          mmo1.Lines.Add('接收到:' +BytestoHexString(b,length(b)));
        finally
          IdTCPClient1.Disconnect;
        end;
      end;
    end;

    服务端

        IdTCPServer1: TIdTCPServer;
        Button1: TButton;
        Memo1: TMemo;

    procedure TForm4.Button1Click(Sender: TObject);
    begin
      if  IdTCPServer1.Active then
         IdTCPServer1.Active:= False;
      IdTCPServer1.Bindings.Clear;
      with IdTCPServer1.Bindings.Add do
      begin
        ip:= '0.0.0.0';
        Port:= 8090;
      end;
      IdTCPServer1.DefaultPort:= 8090;
      IdTCPServer1.Active:= True;

      Memo1.Lines.Add('服务器监听已启动!')
    end;

    procedure TForm4.IdTCPServer1Execute(AContext: TIdContext);
    var
      Cmd:string;
      b:TBytes;
    begin
      if not AContext.Connection.IOHandler.Connected then
      begin
        Exit;
      end;
      try
        Cmd:= AContext.Connection.IOHandler.ReadLn;
        Memo1.Lines.Add('接收到数据:'+Cmd);
        if Cmd = 'QUERYDATA' then
        begin
          setlength(b,2);
          b[0]:= 1;
          b[1]:= 2;
          AContext.Connection.IOHandler.Write(b);
          Memo1.Lines.Add('发送:'+BytestoHexString(b,Length(b)));
        end;
      except
         Exit;
      end;
    end;

  • 相关阅读:
    MySQL Explain学习笔记
    postman测试文件上传接口教程
    URLDecoder异常Illegal hex characters in escape (%)
    第三章 jQuery总结 参考文本
    史上最简单的一道面试题!坑人吧
    cookie和session的关联关系
    服务器配置
    Rancher 添加主机无法显示、添加主机无效的解决办法
    .NET Core 跨平台 串口通讯 ,Windows/Linux 串口通讯,flyfire.CustomSerialPort 的使用
    .Net Core 跨平台应用使用串口、串口通信 ,可能出现的问题、更简洁的实现方法
  • 原文地址:https://www.cnblogs.com/liujicai/p/4455519.html
Copyright © 2011-2022 走看看