UDP聊天工具的实现
利用TIdUDPClient; TIdUDPServer; 实现聊天,其实很不爽,没有解决中文乱码问题,以后补充吧!
代码如下:
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, IdUDPServer, IdBaseComponent, 8 IdComponent, IdUDPBase, IdUDPClient, Vcl.ExtCtrls, Vcl.StdCtrls,IdGlobal, 9 IdSocketHandle; 10 type 11 TForm1 = class(TForm) 12 Memo1: TMemo; 13 Memo2: TMemo; 14 GroupBox1: TGroupBox; 15 Button1: TButton; 16 LabeledEdit1: TLabeledEdit; 17 Button2: TButton; 18 LabeledEdit3: TLabeledEdit; 19 LabeledEdit4: TLabeledEdit; 20 Button3: TButton; 21 IdUDPClient1: TIdUDPClient; 22 IdUDPServer1: TIdUDPServer; 23 procedure Button2Click(Sender: TObject); 24 procedure Button3Click(Sender: TObject); 25 procedure Button1Click(Sender: TObject); 26 procedure IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; 27 const AData: TIdBytes; ABinding: TIdSocketHandle); 28 private 29 { Private declarations } 30 public 31 { Public declarations } 32 end; 33 34 var 35 Form1: TForm1; 36 37 implementation 38 39 {$R *.dfm} 40 procedure TForm1.Button2Click(Sender: TObject); //监听 41 begin 42 IdUDPServer1.DefaultPort := StrToInt(LabeledEdit1.Text); 43 IdUDPServer1.Active := True; 44 end; 45 46 procedure TForm1.Button3Click(Sender: TObject); //假装连接 47 begin 48 IdUDPClient1.Host := LabeledEdit3.Text; 49 IdUDPClient1.Port := StrToInt(LabeledEdit4.Text); 50 end; 51 52 procedure TForm1.Button1Click(Sender: TObject); //发送 53 begin 54 idUDPClient1.Send(memo2.Text); 55 end; 56 57 procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; //接收 58 const AData: TIdBytes; ABinding: TIdSocketHandle); 59 var 60 str:string; 61 begin 62 //str:= IdUDPServer1.ReceiveString(); 或者 63 //Memo1.Lines.Add(str); 64 str:= BytesToString(AData); 65 Memo1.Lines.Add(str); 66 end; 67 68 end.