whats new ¦  programming tips ¦  indy articles ¦  intraweb articles ¦  informations ¦  links ¦  interviews
 misc ¦  tutorials ¦  Add&Win Game

Tips (1541)

Database (90)
Files (137)
Forms (107)
Graphic (114)
IDE (21)
Indy (5)
Internet / LAN (130)
IntraWeb (0)
Math (76)
Misc (126)
Multimedia (45)
Objects/
ActiveX (51)

OpenTools API (3)
Printing (35)
Strings (83)
System (266)
VCL (242)

Top15

Tips sort by
component


Search Tip

Add new Tip

Add&Win Game

Advertising

23 Visitors Online


 
...Use TcpClient/Server for a Chat?
Autor: Scas...
[ Print tip ]  

Tip Rating (137):  
     


{*********************************************************************
 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.


 

Rate this tip:

poor
very good


Copyright © by SwissDelphiCenter.ch
All trademarks are the sole property of their respective owners