找了點資料看了下,於是自己動手做了一個練習一下,
主要用到TServerSocket和TClientSocket這個控件。
客戶端:
var Form1: TForm1; NewTime:string; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ClientSocket1.Host:=Trim(Edit1.Text); //連接服務端地址 ClientSocket1.Port:=57124; //連接的端口號 ClientSocket1.Open; //開始連接 Button1.Enabled:=False; end; procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket); var Str:string; begin //讀取服務端發過來的數據 str:=ClientSocket1.Socket.ReceiveText; Memo1.Lines.Add(Str); end; procedure TForm1.Button2Click(Sender: TObject); var Msg:string; begin Msg:=Trim(Edit2.Text); Memo1.Lines.Add('王四:' + NewTime + #10); Memo1.Lines.Add(Msg); ClientSocket1.Socket.SendText('王四:' + NewTime +#13#10); ClientSocket1.Socket.SendText(Msg); //發送給服務端 end; procedure TForm1.Timer1Timer(Sender: TObject); begin NewTime:=TimeToStr(Now); end;
服務端:
var Form1: TForm1; NewTime:string; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ServerSocket1.Port:=57124; //監聽端口 ServerSocket1.Open; //開始監聽 Button1.Enabled:=False; end; procedure TForm1.Button2Click(Sender: TObject); var Str:string; i : integer; begin Str:=Trim(Edit2.Text); for i:=0 to ServerSocket1.Socket.ActiveConnections-1 do begin Memo1.Lines.Add('張三:' + NewTime + #10); Memo1.Lines.Add(Str); ServerSocket1.Socket.Connections[i].SendText('張三:' + NewTime +#13#10); //發送數據 ServerSocket1.Socket.Connections[i].SendText(Str); end; end; procedure TForm1.ServerSocket1ClientRead(Sender: TObject; Socket: TCustomWinSocket); //讀取客服端發來的數據 var Msg:string; begin Msg:=Socket.ReceiveText; Memo1.Lines.Add(Msg); end; procedure TForm1.Timer1Timer(Sender: TObject); begin NewTime:=TimeToStr(Now); end;
運行圖: