看看delphi自带的demo就行了。
unit file:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ScktComp;
type
TForm1 = class(TForm)
ClientSocket1: TClientSocket;
ServerSocket1: TServerSocket;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
ClientSocket1.Open;
Sleep(2000); //wait for connect to serversocket
Application.ProcessMessages;
ClientSocket1.Socket.SendText('this is a test') ;
ClientSocket1.Close;
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
begin
ShowMessage(Socket.ReceiveText);
end;
end.
form file:
object Form1: TForm1
Left = 192
Top = 114
Width = 275
Height = 269
Caption = 'Form1'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 88
Top = 120
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
object ClientSocket1: TClientSocket
Active = False
Address = '127.0.0.1'
ClientType = ctNonBlocking
Port = 9999
Left = 104
Top = 64
end
object ServerSocket1: TServerSocket
Active = True
Port = 9999
ServerType = stNonBlocking
OnClientRead = ServerSocket1ClientRead
Left = 152
Top = 64
end
end