【发布时间】:2013-06-18 05:44:53
【问题描述】:
我有两个使用 TCPServer 和 TCPClient 组件相互通信的应用程序。
服务器以隐藏模式启动:Application.ShowMainForm: = false;
只是系统托盘上的一个图标与用户交互。运行服务器后,如果我运行客户端并连接到服务器,则会冻结,但如果我将服务器属性 Application.ShowMainForm 更改为 true 一切正常。这是我正在使用的代码:
客户端应用:
procedure TFormCliente.FormCreate(Sender: TObject);
begin
try
cliente.Connect;
except
hint1.ActivateHint(FormCliente,'Error.' + #13 +
'Verify if server is running','VCall',5000); //hint1 is a Jed component
end;
end;
服务器应用:
[...]
private
FConexoes: TList;
[...]
type
PClient = ^TClient;
TClient = record
PeerIP : string[15]; { Client IP address }
HostName : String[40]; { Hostname }
Connected, { Time of connect }
LastAction : TDateTime; { Time of last transaction }
AContext : Pointer; { Pointer to thread }
end;
[...]
procedure TfrmServer.FormCreate(Sender: TObject);
begin
FConexoes := TList.Create;
end;
procedure TFrmServer.FormDestroy(Sender: TObject);
begin
FConexoes.Free;
end;
procedure TFrmServer.IdTCPServer1Connect(AContext: TIdContext);
var
NewClient: PClient;
begin
GetMem(NewClient, SizeOf(TClient));
NewClient.PeerIP := AContext.Connection.Socket.Binding.PeerIP;
NewClient.HostName := GStack.HostByAddress(NewClient.PeerIP);
NewClient.Connected := Now;
NewClient.LastAction := NewClient.Connected;
NewClient.AContext := AContext;
AContext.Data := TObject(NewClient);
ListView1.Items.Add.Caption:=NewClient.HostName;
end;
如果服务器表单可见,则将客户端主机名添加到列表视图中,但如果服务器表单不可见,则运行 cliente 并连接,服务器将冻结,直到我终止客户端进程。谁能帮帮我?
【问题讨论】:
-
这对我来说没问题。当我关闭客户端(即断开连接)时收到异常,但处理 AContext.Data 并将其设置为 nil 解决了该问题。也许与此有关。
-
Indy 事件是多线程的,永远不要从主线程以外的线程更新 GUI,您必须调用 Synchronize() 来更新 GUI。
-
Whosrdaddy 那么我该怎么做呢?从线程中放置 ButtonX.click 是更新 GUI 的替代方法?
-
访问
TListView的行不是线程安全的。使用TThread.Synchronize()方法或TIdSync类安全地调用该行。 -
@RemyLebeau 请写一个例子...
标签: delphi delphi-2010