【问题标题】:Delphi xe-3 indy 10 unable to read data tidudpserver onudpreadDelphi xe-3 indy 10 无法读取数据 tidudpserver onudpread
【发布时间】:2013-08-02 21:04:28
【问题描述】:

我正在为客户端和服务器使用 tidudpserver。下面是给出的服务器和客户端代码。

unit udp_server;



procedure TForm4.serverUDPRead(AThread: TIdUDPListenerThread;
  AData: array of Byte; ABinding: TIdSocketHandle);
var
  buffer:tbytes;
  buffer2:tbytes;
  i:integer;
  ex_port:word;
  i_ip,ex_ip:string;
  t: string;
begin
   ex_ip:=abinding.PeerIP;      //public_ip
   ex_port:=abinding.PeerPort;   //public_port

   //byte  to string
   setlength(i_ip,length(adata) div 2);  

   // extract private ip from array of byte
   move(Adata[0],i_ip[1],length(adata)); 

   // client profile  {object of tclient }
   user:=tclient.create(ex_ip,ex_port,i_ip,0,''); 
   //copying public and private    endpoints to tclient object


   setlength(buffer,sizeof(user));         
   move(user,buffer[0],sizeof(user)); // copying object to byte array 


   server.Sendbuffer(abinding.PeerIP,abinding.PeerPort,buffer); 
   // send client info to all connected clients(is this correct way of sending buffer(byte array)?)
end;

这是给定的客户端代码。我无法读取服务器在onudpread 过程中发送的数据。如何将字节数组(包含字符串和单词类型)转换为可读文本?

unit udp_client;



procedure TForm4.server2UDPRead(AThread: TIdUDPListenerThread;
  AData: array of Byte; ABinding: TIdSocketHandle);
var
  dest:string;
  user2:tclient;// i had a tclient class in a separate file
  buffer:tbytes;
begin


  setlength(dest,length(adata));
  move(Adata[0],dest[1],length(adata));  // problem is over here ,is this correct?
end;

客户端发送的私有ip

              ip:=getipaddress; //call private ip function taken from (http://delphi.about.com/od/networking/l/aa103100a.htm)

              setlength(i_ip,length(ip)*2);

              move(ip[1],i_ip[0],length(i_ip));

              server2.Sendbuffer('host',port,i_ip); 

我想做 udp 打孔,因为客户端需要将他们的信息(公共/私有 ip/端口)发送到服务器,然后服务器将交换客户端信息,然后他们应该能够聊天。我很困惑,因为 adata 数组是接收所有数据,ip 和短信会相互混合吗?目前我正在接收垃圾值,就像中文一样。:-/

【问题讨论】:

  • edit您的问题删除所有用户界面代码(与您的问题无关)。使用与您的问题无关的所有额外代码来弄清楚您在问什么要困难得多。谢谢。

标签: delphi indy delphi-xe3


【解决方案1】:

这段代码有一些问题。

在服务器代码中,将接收到的数据复制到String 时,您将错误的大小值传递给Move()。调用SetLength() 时考虑SizeOf(Char)=2,但调用Move() 时不考虑。并且仅当接收到的数据以 UTF-16 开头(您没有显示接收到的数据的实际外观)时才考虑 Sizeof(Char) 是正确的。

一个更大的问题是你试图向客户端发送一个对象,这永远不会奏效。您必须将对象的各个数据成员序列化为平面可传输格式,然后改为发送该数据。例如,IdGlobal 单元具有许多可用于进行数据字节转换的函数(ToBytes() 重载、BytesTo...() 重载、CopyTId...() 重载等)。因此,您可以分配一个足够大的TIdBytes 来保存对象的所有数据,用数据填充它,然后发送它。收到后,再次将其拆分为单独的值。您实际上如何执行所有这些操作取决于您首先尝试发送的数据类型(您也没有表明这一点)。

如果您需要更具体的示例,则需要说明您实际尝试来回交换的数据类型。

【讨论】:

    【解决方案2】:

    尝试使用 StringOf 函数。它适用于 TBytes 类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多