サンプルアプリケーション02:チャットアプリケーション

作成するアプリケーションについて

複数の端末で文字列を相互にやりとりするチャットアプリケーションを作成します。

_images/005.gif

アプリケーションの作成

プロジェクトの作成

新規にFireMonkeyモバイルアプリケーションを作成します。

_images/201.gif

フォームの作成

次のようにコンポーネントを配置します。

  • TListBox … Align=Client
  • TPanel … Align=Top
    • TLabel … Align=Client
    • TButton … Align=Right
  • TPanel … Align=Top
    • TEdit … Align=Client
    • TButton … Align=Right
  • TTetheringAppProfile
  • TTetheringManager
  • TTimer
_images/202.gif
_images/203.gif

接続処理

Button1のTextプロパティを「接続」に変更します。

_images/204.gif

Button1(接続ボタン)のOnClickイベントを追加します。

procedure TForm1.Button1Click(Sender: TObject);
begin
  TetheringManager1.AutoConnect();
end;

TetheringAppProfile1のプロパティを設定します。

  • Managerプロパティ … TetheringManager1
  • Groupプロパティ … SampleChatGroup
  • Textプロパティ … SampleChatProfile

設定したGroupプロパティとTextプロパティの値は、送信先の識別に使用します。

_images/205.gif

Timer1のOnTimerイベントを追加します。

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if TetheringManager1.RemoteProfiles.Count > 0 then
  begin
    Label1.Text := '接続中';
  end
  else
  begin
    Label1.Text := '接続していません。';
  end;
end;

動作確認

ここまで完成したら、動作を確認します。

アプリケーションを2つ以上起動します。 起動したら、「接続」ボタンを押します。 接続に成功したら、ラベルに「接続中」と表示されます。

_images/206.gif

文字列の送受信

入力した文字列を送信する処理を追加します。

文字列の送信

Button2のTextプロパティを「送信」に変更します。

_images/207.gif

Button2のOnClickイベントを追加します。

接続しているプロファイルのうち、Groupプロパティが「SampleChatGroup」でTextプロパティが「SampleChatProfile」であるプロファイルに対して、ヒント文字列に「コメント」、送信文字列にEdit1に入力された文字列を送信します。

procedure TForm1.Button2Click(Sender: TObject);
var
  RemoteProfile: TTetheringProfileInfo;
begin
  ListBox1.Items.Add(Edit1.Text);

  for RemoteProfile in TetheringManager1.RemoteProfiles do
  begin
    if (RemoteProfile.ProfileGroup = 'SampleChatGroup') and
      (RemoteProfile.ProfileText = 'SampleChatProfile') then
    begin
      TetheringAppProfile1.SendString(RemoteProfile, 'コメント', Edit1.Text);
    end;
  end;
end;

文字列の受信

送信された文字列を受信します。

TetheringAppProfile1のOnResourceReceivedイベントを追加します。

procedure TForm1.TetheringAppProfile1ResourceReceived(const Sender: TObject;
  const AResource: TRemoteResource);
begin
  TThread.Synchronize(nil, procedure
  begin
    ListBox1.Items.Add(AResource.Value.AsString);
  end);
end;

ここでは、送信されたデータが文字列であることがわかっているため、データの型をチェックしていません。

動作確認

ここまで完成したら、動作を確認します。

アプリケーションを2つ以上起動します。 起動したら、「接続」ボタンを押して、接続します。

接続したら、入力欄に文字列を入力して、「送信」ボタンを押します。 入力した文字列が他のアプリケーションに表示されたら成功です。