Habari Chat is a demo application for the Habari Client libraries, available with full source code and as executable in the demo downloads.
Sending broadcast messages
After choosing a chatroom name and a nickname, the user interface allows to send text messages. For system messages – for example when users enter or leave a chatroom – the code below is used:
procedure TMainForm.SendPublicInfo(const MsgText: string); var Msg: IMessage; begin Msg := Session.CreateTextMessage(MsgText); Producer.Send(Msg); end;
Sending messages with nickname
For user messages, the code is almost the same. One additonal line of code sets a custom message property to the sender nickname:
procedure TMainForm.SendPublicInfo(const MsgText: string); var Msg: IMessage; begin Msg := Session.CreateTextMessage(MsgText); Msg.SetStringProperty('nickname', NickName); Producer.Send(Msg); end;
Receiving messages
Incoming messages will be handled by an asynchronous event handler. (For real world applications, using a separate receive thread is recommended, which makes handling of lost connections easier.)
procedure TMainForm.OnMessage(const AMessage: IMessage); var SenderNick: string; TxtMsg: ITextMessage; begin SenderNick := AMessage.GetStringProperty('nickname'); if Supports(AMessage, ITextMessage, TxtMsg) then begin if SenderNick <> '' then MemoChat.Lines.Add(SenderNick + ': ' + TxtMsg.Text) else MemoChat.Lines.Add(TxtMsg.Text) end else begin raise Exception.Create('Expected ITextMessage'); end; end;
Conclusion
This example application shows that creating Delphi chat applications based on existing open source message brokers requires little code. The complete sourcecode in MainFrm.pas counts less than 200 lines of code.
Such a compact application is possible because Habari Client libraries provide the high level API to create connections, message consumers / message producers and messages, while the message broker process provides the reliable messaging infrastructure.
Discover more from Habarisoft Blog
Subscribe to get the latest posts sent to your email.