有个地方比较奇怪,我点击主控端的连接,第1次总是不行,第2次却都能连上,而连上后点发送按钮第一次也会出错,第2次就能正常发送消息了!不知道为什么?还有,怎么才能判断于客户端连上了,因为是在局域网,要对所有的机子做一次搜索,所以要能列出连上的机子!以下是代码
=========TcpClient部分============
procedure TForm1.TcpClient1Error(Sender: TObject; SocketError: Integer);
begin
Application.MessageBox(Pchar('不能连接到IP地址 : ' + Edit2.Text+ ' 。'+ #13+'可能是监听程序没有运行或网络故障!'),'Client 连接错误',MB_OK+MB_ICONSTOP);
end;procedure TForm1.BtnSendClick(Sender: TObject);
begin
with TcpClient1 do
begin
try
Active:= True;
RemoteHost := Edit2.Text;
TcpClient1.Sendln(Edit1.Text);
finally
Disconnect;
end;
end
end;procedure TForm1.BtnConnectClick(Sender: TObject);
begin
TcpClient1.Active:= True;
end;
==========TcpServer部分==========
procedure TForm1.TcpServer1Accept(Sender: TObject;
ClientSocket: TCustomIpClient);
var
s: string;
begin
s := ClientSocket.Receiveln;
Application.MessageBox(Pchar(s),'提示',0);
end;
=========TcpClient部分============
procedure TForm1.TcpClient1Error(Sender: TObject; SocketError: Integer);
begin
Application.MessageBox(Pchar('不能连接到IP地址 : ' + Edit2.Text+ ' 。'+ #13+'可能是监听程序没有运行或网络故障!'),'Client 连接错误',MB_OK+MB_ICONSTOP);
end;procedure TForm1.BtnSendClick(Sender: TObject);
begin
with TcpClient1 do
begin
try
Active:= True;
RemoteHost := Edit2.Text;
TcpClient1.Sendln(Edit1.Text);
finally
Disconnect;
end;
end
end;procedure TForm1.BtnConnectClick(Sender: TObject);
begin
TcpClient1.Active:= True;
end;
==========TcpServer部分==========
procedure TForm1.TcpServer1Accept(Sender: TObject;
ClientSocket: TCustomIpClient);
var
s: string;
begin
s := ClientSocket.Receiveln;
Application.MessageBox(Pchar(s),'提示',0);
end;
begin
with TcpClient1 do
begin
try
RemoteHost := Edit2.Text;
if Connect then
Sendln(Edit1.Text);
finally
Disconnect;
end;
end
end;
如果非阻塞就用ServerSocket
http://www.indyproject.org/download/Borland.iwp