unit TcpSCDemo;
//最简单的TTcpServer与TTcpClient通信实例-Delphi
//Borland推出TTcpServer与TTcpClient作为主要的网络通信控件,意味着这两个控件有很大的优越性,
//但是有关这两个控件的资料非常少见,很多人都在问一个相同的问题:TcpServer怎么样向TcpClient发送数据?
//网上的回答千奇百怪,归纳起来有三种:
//1.参考delphi自带的netchat.例子中TcpServer只收不发,答题得分0.
//2.用indy或者ServerSocket/ClientSocket来说事.牛头不对马嘴,答题得分0.
//3.建议使用indy或者ServerSocket/ClientSocket,有道理,也管用,但是回答的不是正题,答题得分59.
//今天我要给出的例子就是用TTcpServer与TTcpClient进行双向通信,相信看过以后就会,答题得分99.
//为什么不是100呢?因为太简单!
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Sockets, StdCtrls;
type
//工作流程:
//程序运行后点[连接]连接TcpClient和TcpServer
//点[发送]将edit1中的文本发送到TcpServer,TcpServer接收到以后添加到Mserver,并回复一条消息.
//TcpClient1收到TcpServer回复的消息后添加到TcpServer
//所有控件都说到了吧?Let's Go!
TFrmMain = class(TForm)
Edit1: TEdit;
Button1: TButton; //连接
Button2: TButton; //发送
Mserver: TMemo;
MClient: TMemo;
TcpServer1: TTcpServer; //active:=True;host:=127.0.0.1;port:=2011;其它默认值
TcpClient1: TTcpClient; //remotehost:=127.0.0.1;remoteport:=2011;其它默认值
procedure TcpServer1Accept(Sender: TObject;
ClientSocket: TCustomIpClient);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
//这个类实现TTcpClient接收TTcpserver回复的消息
TClientReceiveThread = class(TThread)
procedure Execute; override;
end;
var
FrmMain: TFrmMain;
ClientReceiveThread: TClientReceiveThread;
implementation
{$R *.dfm}
procedure TClientReceiveThread.Execute;
begin
with FrmMain do
begin
while TcpClient1.Connected do //死循环!必须的!!!
MClient.Lines.Add(TcpClient1.Receiveln);
end;
end;
//TcpServer1的OnAccept事件
procedure TFrmMain.TcpServer1Accept(Sender: TObject;
ClientSocket: TCustomIpClient);
var
s: String;
begin
while ClientSocket.connected do //死循环!必须的!!!
begin
s := ClientSocket.Receiveln; //收
MServer.Lines.Add(s);
s := DateTimeToStr(Now);
ClientSocket.Sendln(s); //发
end;
end;
procedure TFrmMain.Button1Click(Sender: TObject);
begin
//连接服务器,如果成功创建客户端接收线程
if TcpClient1.Connect then ClientReceiveThread := TClientReceiveThread.Create(false);
end;
procedure TFrmMain.Button2Click(Sender: TObject);
begin
TcpClient1.Sendln(Edit1.Text);
end;
//真的很简单,最后一句话:
end.