Saturday, February 5, 2011

How to use TcpClient/server for a chat

In this example you will know how to use TcpClient/Server component
to make a simple chat, remember that i just give you a base, so you
can improve it Adding, Removing, or Changing what you want.
(TcpClient/Server is in Internet Palette in Delphi 7)

unit TcpConnection;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes,
  Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
  Sockets;

type
  ...Host1: TEdit;
  RPort: TEdit;
  LPort: TEdit;
  Lines1: TEdit;
  ChatWnd: TMemo;
  ......TcpClient1: TTcpClient;
  TcpServer1: TTcpServer;
procedure Connect1Click(Sender: TObject);
procedure Send1Click(Sender: TObject);
procedure TcpServer1Accept(Sender: TObject;
  ClientSocket: TCustomIpClient);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Connect1Click(Sender: TObject);
begin
  TcpServer1.Active    := False; {Disconnect First}
  TcpServer1.LocalPort := LPort.Text;
  TcpServer1.Active    := True; {Then Connect}
end;

procedure TForm1.Send1Click(Sender: TObject);
begin
  TcpClient1.RemoteHost := Host1.Text;
  {To connect  to Server you must know his IP address, like 255.255.255.255}
  TcpClient1.RemotePort := RPort.Text;

  try
    if TcpClient1.Connect then
      TcpClient1.Sendln(Lines1.Text);
  finally
    TcpClient1.Disconnect;
  end;
end;

{OnAccept Event}

procedure TForm1.TcpServer1Accept(Sender: TObject;
  ClientSocket: TCustomIpClient);
var
  s: string;
begin
  ChatWnd.Lines.Add('Start Sending Data');
  ChatWnd.Lines.Add('Rem Host: ' +
    ClientSocket.LookupHostName(ClientSocket.RemoteHost) + ' (' + ClientSocket.RemoteHost + ')');
  s := ClientSocket.Receiveln;
  while s <> '' do
  begin
    ChatWnd.Lines.Add(s);
    s := ClientSocket.Receiveln;
  end;
  ChatWnd.Lines.Add('End Sending Data');
end;

end.


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Kang Iwan K-sev | Thank's for your visit To My Site - Ridwan Mulyana | Cibeureum