Broadcast Chat sample (Delphi)

Overview

This sample shows how to use the Indy-based channels TROBroadcastServer and TROBroadcastChannel to write an UDP broadcasting chat program.

Getting started

Compile the project. The resulting application combines the client and the server, so in order to test this sample, you need to deploy the compiled .exe on two or more computers.

Note: If you are running a trial version of the RemObjects SDK, you need to have the Delphi IDE running on each machine due to trial version limitations.

Examine the code

  • See how the client gets the list of users by performing an asynchronous call to the server method:
procedure TBroadcastChatMainForm.BitBtn1Click(Sender: TObject);
begin
  fChatProxy.Invoke_GetInfo();
end;

and then retrieves the answer in the OnBroadcastResponseReceived event:

procedure TBroadcastChatMainForm.ROBroadcastChannelBroadCastResponseReceived(aServerIP, aResponseUID: string);
var
  lName: string;
begin
  lName := fChatProxy.Retrieve_GetInfo();
  ed_Chat.Lines.Add(Format('[%s] chat user: %s (at %s)', [TimeToStr(Now), lName, aServerIP]));
end;
  • Sending messages is implemented by using another asynchronous call:
procedure TBroadcastChatMainForm.ac_SendMessageExecute(Sender: TObject);
begin
  if ed_Message.Text <> '' then begin
    fChatProxy.Invoke_SendMessage(Now, ed_NickName.Text, ed_Message.Text);
    ed_Message.Text := '';
    ActiveControl := ed_Message;
  end;
end;

Due to specifics of the broadcast channel, the call is processed by all chat applications in the LAN. The service implementation method is responsible for adding the new text to the chat window:

procedure TBroadcastChatService.SendMessage(const iDate: DateTime; const iFrom: UnicodeString; const iMessage: UnicodeString);
begin
  fSync_Date := iDate;
  fSync_From := iFrom;
  fSync_Message := iMessage;
{$IFDEF VER140}
  Windows.SendMessage(BroadcastChatMainForm.Handle, WM_USER, Longint(Self), 0); // workaround for d6
{$ELSE}
  Synchronize(MessageReceived);
{$ENDIF}
end;

Notice the Windows messages used to manipulate the GUI, it is necessary because this code is executed on a background thread.