由于本人天生愚钝,所以关于聊天工具的编程一直都没学会,尽管网上教程一大堆,但是关于IdTCPClient  IdTCPServer 的不多,今天终于学会一些,分享给像我一样纠结的小伙伴,下一步学习多线程的聊天工具!

  界面如图:memo 2个  button 3个  labelEdit 3个 IdTCPClient  1个   IdTCPServer 1个 

 TCP聊天工具的实现-LMLPHP

 代码如下:

 

 unit Unit1;

 interface

 uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
IdCustomTCPServer, IdTCPServer, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdContext,IdGlobal; type
TForm1 = class(TForm)
Memo1: TMemo;
GroupBox1: TGroupBox;
LabeledEdit1: TLabeledEdit;
LabeledEdit2: TLabeledEdit;
Button2: TButton;
Button3: TButton;
Label1: TLabel;
Memo2: TMemo;
IdTCPClient1: TIdTCPClient;
IdTCPServer1: TIdTCPServer;
GroupBox2: TGroupBox;
LabeledEdit3: TLabeledEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure IdTCPServer1Connect(AContext: TIdContext);
procedure Button3Click(Sender: TObject);
procedure IdTCPServer1Execute(AContext: TIdContext);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end; var
Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); //监听
begin
IdTCPServer1.DefaultPort := StrToInt(LabeledEdit3.Text); //本地端口
IdTCPServer1.Active := True; //打开监听
end; procedure TForm1.Button2Click(Sender: TObject); //远程连接
begin
if not IdTcpClient1.Connected then
begin
IdTCPClient1.Host := LabeledEdit1.Text;
IdTCPClient1.Port := StrToInt(LabeledEdit2.Text);
IdTCPClient1.Connect;
IdTCPClient1.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8(); //中文处理 uses IdGlobal;
end;
end; procedure TForm1.IdTCPServer1Connect(AContext: TIdContext); //有用户连接时候通知
begin
Memo1.Lines.Add('有朋友连接:');
Memo1.Lines.Add(' ');
AContext.Connection.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8(); //中文处理 uses IdGlobal;
end; procedure TForm1.Button3Click(Sender: TObject); //发送信息
begin
IdTCPClient1.IOHandler.writeln('皮皮说:'+ Memo2.Text);
end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); //关闭时断开连接
begin
IdTcpClient1.Disconnect;
end; procedure TForm1.IdTCPServer1Execute(AContext: TIdContext); //接收信息
var
recstr:string;
begin
recstr := AContext.Connection.IOHandler.ReadLn;
Memo1.Lines.Add(recstr);
end; end.

  

  

05-07 15:56