【问题标题】:Indy UDP sending and responding simple stringsIndy UDP 发送和响应简单字符串
【发布时间】:2017-06-28 23:20:26
【问题描述】:

我正在使用 Delphi 10.0 Seattle。

我想向 UDP 服务器发送请求,然后读取服务器响应,这是一个简单的字符串:

Client side:send('12345')
server side(onread event or whatever):if received string =  ('12345') then 
send ('jhon|zack|randy')
else disconnect;

响应字符串的长度是可变的。

服务器正在一个开放连接的网络上运行(专用 vps)。 客户端不一样,它在路由器和安全网络后面(不转发)。

到目前为止,我只能从客户端发送请求:

(uc=idUDPclient)

procedure TForm1.Button1Click(Sender: TObject);
var
  s:string;
begin
  if uc.Connected =False then
    Uc.Connect;
  uc.Send('12345');
  uc.ReceiveTimeout := 2000;
  s:=uc.ReceiveString() ;
  ShowMessage(s);
  uc.Disconnect
end;

服务器端(us=idUDPserver)

procedure TForm1.usUDPRead(AThread:TIdUDPListenerThread;const AData: TIdBytes;ABinding: TIdSocketHandle);
begin
  ShowMessage(us.ReceiveString());

  if us.ReceiveString() = '12345' then
  begin
    ShowMessage(us.ReceiveString());

    //respond with a string to the client immediately (behind a routers) how ?
  end;

不知道TCP是否更好,如何使用。

Android 将参与其中。

【问题讨论】:

标签: delphi udp indy delphi-10-seattle


【解决方案1】:

您没有正确使用TIdUDPServer.OnUDPRead 事件。您需要摆脱对ReceiveString() 的呼叫,它们不属于那里。请改用AData 参数,它包含客户端请求的原始字节。 TIdUDPServer 在触发事件处理程序之前已经读取了客户端的数据。

如果您需要 string 中的字节,可以使用 Indy 的 BytesToString() 函数或 IIdTextEncoding.GetString() 方法。

要将响应发送回客户端,请使用ABinding参数。

试试这个:

procedure TForm1.usUDPRead(AThread: TIdUDPListenerThread;
  const AData: TIdBytes; ABinding: TIdSocketHandle);
var
  s: string;
begin
  s := BytesToString(AData);
  //ShowMessage(s);
  if s = '12345' then begin
    ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, 'jhon|zack|randy', ABinding.IPVersion);
  end;
end;

【讨论】:

  • 完美就是这样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 2023-03-19
  • 2018-08-07
  • 2015-01-21
  • 1970-01-01
相关资源
最近更新 更多