How can I send a broadcast message in Delphi

旧时模样 提交于 2019-11-29 15:47:31

问题


I want to send a broadcast UDP message in my LAN, the application is client/server.

I desire to update the user interface, this way any computer send a message to update the others. Can I use UDPServer indy, how to use ? Thanks


回答1:


Create two applications, one represents the sender and the other the receiver.

Sender

Drop a TIdUDPClient and a TButton component on your form. On the OnClick handler of the button write:

procedure TfrmUDPClient.BroadcastClick(Sender: TObject);
begin
  UDPClient.Broadcast('Test', 8090);
end;

Receiver

Drop a TIdUDPServer on your form, define the same port (8090) for it and add this to the OnUDPRead handler:

procedure TfrmUDPServer.UDPServerUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
var
  DataStringStream: TStringStream;
  Msg: String;
begin
  DataStringStream := TStringStream.Create('');
  try
    DataStringStream.CopyFrom(AData, AData.Size);
    Msg := DataStringStream.DataString;
  finally
    DataStringStream.Free;
  end;
  ShowMessage(Msg);
end;

Or, in later versions of Indy:

procedure TfrmUDPServer.UDPServerUDPRead(AThread: TIdUDPListenerThread;
  const AData: TIdBytes; ABinding: TIdSocketHandle);
var
  Msg: String;
begin
  try
    {if you actually sent a string encoded in utf-8}
    Msg := TEncoding.UTF8.GetString(AData);
  except
  end;

  ShowMessage(Msg);
end;

To test, run both applications and click on the button. To test with two or more "listeners" you have to use another machine. That is, you can't run multiple listeners on the same IP.




回答2:


Create a TIdUDPServer or TIdUDPClient component. Both have Broadcast methods that should do exactly what you need.



来源:https://stackoverflow.com/questions/3480729/how-can-i-send-a-broadcast-message-in-delphi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!