我有个用INDY组件做的C/S模型.给你参考下:
客户端:
procedure TForm1.Button1Click(Sender: TObject);
begin
IdTCPClient1.Host:=Edit1.Text;
IdTcpClient1.Port:=StrToInt(Edit2.Text);
ListBox1.Items.Add('正在连接'+Edit1.Text+'...');
with IdTCPClient1 do
begin
try
connect(2000);
try
ListBox1.Items.Add(ReadLn());
Button1.Enabled:=False;
Button2.Enabled:=True;
Button3.Enabled:=True;
except
ListBox1.Items.Add('远程主机无响应!') ;
IdTCPClient1.Disconnect();
end;
except
ListBox1.Items.Add('无法建立到'+Edit1.Text+'的连接');
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
ListBox1.Items.Add('DATA'+Edit3.Text);
with IdTCPClient1 do
begin
try
WriteLn('DATA'+' '+trim(Edit3.Text));
ListBox1.Items.Add(ReadLn());
except
ListBox1.Items.Add('发送数据失败!');
IdTCPClient1.Disconnect();
ListBox1.Items.Add('同主机'+Edit1.Text+'的连接已断开!');
Button1.Enabled:=True;
Button2.Enabled:=False;
Button3.Enabled:=False;
end;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
Received:string;
begin
ListBox1.Items.Add('QUIT');
try
IdTCPClient1.WriteLn('QUIT');
finally
IdTCPClient1.Disconnect();
ListBox1.Items.Add('同主机'+Edit1.Text+'的连接已断开!');
Button1.Enabled:=True;
Button2.Enabled:=False;
Button3.Enabled:=False;
end;
end;
end.
服务端:
procedure TForm1.Button1Click(Sender: TObject);
begin
IdTCPServer1.DefaultPort:=StrToInt(Edit1.Text);
IdTCPServer2.DefaultPort:=StrToInt(Edit3.Text);
IdTCPServer1.Active:=True;
IdTCPServer2.Active:=True;
Button1.Enabled:=False;
Button2.Enabled:=True;
ListBox1.Items.Add('服务器已成功启动!');
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
IdTCPServer1.Active:=False;
IdTCPServer2.Active:=False;
Button1.Enabled:=True;
Button2.Enabled:=False;
ListBox1.Items.Add('服务器已成功停止!');
end;
procedure TForm1.IdTCPServer1Connect(AThread: TIdPeerThread);
begin
ListBox1.Items.Add('来自主机'+AThread.Connection.Socket.Binding.PeerIP+'的连接请求已经被接纳!');
AThread.Connection.WriteLn('100:欢迎连接到简单TCP服务器!');
end;
procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
sCommand,FLogEntry:string;
begin
with AThread.Connection do
begin
sCommand:=ReadLn();
FLogEntry:=sCommand+'来自于主机'+AThread.Connection.Socket.Binding.PeerIP;
AThread.Synchronize(AddLogEntry);
if AnsiStartsText('DATA',sCommand) then
begin
FReceived:=RightStr(sCommand,length(sCommand)-5);
WriteLn(Edit4.Text);
AThread.Synchronize(DisplayData);
end
else if SameText(sCommand,'QUIT') then
begin
FLogEntry:='断开同主机'+AThread.Connection.Socket.Binding.PeerIP+'的连接!';
AThread.Synchronize(AddLogEntry);
Disconnect;
end
{else begin
WriteLn('500:无法识别的命令!');
FLogEntry:='无法识别命令:'+sCommand;
AThread.Synchronize(AddLogEntry);
end;}
end;
end;
procedure TForm1.DisplayData();
begin
Edit2.Text:=FReceived;
Edit4.Text:=FReceived1;
end;
procedure TForm1.AddLogEntry();
begin
ListBox1.Items.Add(FLogEntry);
end;
procedure TForm1.AddLogEntry1();
begin
ListBox1.Items.Add(FLogEntry1);
end;
end.
只是简单的发送接受消息,其他的功能你自己完善!