狼行神码

导航

TCP聊天工具的实现

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

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

 

 代码如下:

 

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 7   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
 8   IdCustomTCPServer, IdTCPServer, IdBaseComponent, IdComponent, IdTCPConnection,
 9   IdTCPClient, IdContext,IdGlobal;
10 
11 type
12   TForm1 = class(TForm)
13     Memo1: TMemo;
14     GroupBox1: TGroupBox;
15     LabeledEdit1: TLabeledEdit;
16     LabeledEdit2: TLabeledEdit;
17     Button2: TButton;
18     Button3: TButton;
19     Label1: TLabel;
20     Memo2: TMemo;
21     IdTCPClient1: TIdTCPClient;
22     IdTCPServer1: TIdTCPServer;
23     GroupBox2: TGroupBox;
24     LabeledEdit3: TLabeledEdit;
25     Button1: TButton;
26     procedure Button1Click(Sender: TObject);
27     procedure Button2Click(Sender: TObject);
28     procedure IdTCPServer1Connect(AContext: TIdContext);
29     procedure Button3Click(Sender: TObject);
30     procedure IdTCPServer1Execute(AContext: TIdContext);
31     procedure FormClose(Sender: TObject; var Action: TCloseAction);
32   private
33     { Private declarations }
34   public
35     { Public declarations }
36   end;
37 
38 var
39   Form1: TForm1;
40 
41 implementation
42 
43 {$R *.dfm}
44 
45 procedure TForm1.Button1Click(Sender: TObject);  //监听
46 begin
47   IdTCPServer1.DefaultPort := StrToInt(LabeledEdit3.Text); //本地端口
48   IdTCPServer1.Active := True;                             //打开监听
49 end;
50 
51 procedure TForm1.Button2Click(Sender: TObject);   //远程连接
52 begin
53   if not IdTcpClient1.Connected then
54   begin
55   IdTCPClient1.Host := LabeledEdit1.Text;
56   IdTCPClient1.Port := StrToInt(LabeledEdit2.Text);
57   IdTCPClient1.Connect;
58   IdTCPClient1.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8(); //中文处理   uses   IdGlobal;
59   end;
60 end;
61 
62 procedure TForm1.IdTCPServer1Connect(AContext: TIdContext);   //有用户连接时候通知
63 begin
64   Memo1.Lines.Add('有朋友连接:');
65   Memo1.Lines.Add('  ');
66   AContext.Connection.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8(); //中文处理    uses   IdGlobal;
67 end;
68 
69 procedure TForm1.Button3Click(Sender: TObject);   //发送信息
70 begin
71   IdTCPClient1.IOHandler.writeln('皮皮说:'+ Memo2.Text);
72 end;
73 
74 procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); //关闭时断开连接
75 begin
76   IdTcpClient1.Disconnect;
77 end;
78 
79 procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);  //接收信息
80 var
81   recstr:string;
82 begin
83   recstr := AContext.Connection.IOHandler.ReadLn;
84   Memo1.Lines.Add(recstr);
85 end;
86 
87 end.

 

 

  

  

posted on 2017-04-28 00:53  狼行神码  阅读(278)  评论(0编辑  收藏  举报