如何在客户端连接的 ListView 中存储标识符 - Indy 10
我正在创建一个 TCP 服务器,它接收多个客户端并且必须能够向每个客户端发送消息。
如何获取客户端连接的句柄然后发送任意数据?
谢谢:D
代码:
procedure TFRM_Main.ServerConnect(AContext: TIdContext);
var lAdd: TListItem;
var Index: integer;
begin
lAdd := ListView.Items.Add;
//AContext connection ID, what to do here?
lAdd.Caption := IntToStr(Index);
end;
I am creating a TCP server which receives multiple clients and must be able to send messages to each.
How do I get a handle to the client connection and then send arbitrary data?
Thanks: D
Code:
procedure TFRM_Main.ServerConnect(AContext: TIdContext);
var lAdd: TListItem;
var Index: integer;
begin
lAdd := ListView.Items.Add;
//AContext connection ID, what to do here?
lAdd.Caption := IntToStr(Index);
end;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
TIdTCPServer
是一个多线程组件。直接从其OnConnect
事件(或OnDisconnect
、OnExecute
或OnException
)内访问 UI 不是线程。安全的!您需要使用 Indy 的TIdSync
或TIdNotify
类来安全地访问 UI。要回答最初的问题,最简单但不一定是最安全的方法是将
TIdContext.Connection
对象指针存储在TListItem.Data
属性中。主线程代码将在需要时直接访问连接。但我不建议这样做。更安全的解决方案是自己唯一地标识每个客户端,例如使用客户端发送的用户名,并将该 ID 存储在
TIdContext.Data
和TListItem.Data
属性中。然后,当您的主线程代码想要向客户端发送消息时,它可以循环遍历TIdTCPServer.Contexts
列表来查找所需的 ID,如果找到,则它将有权访问相应的 <代码>TIdContext.Connection对象。TIdTCPServer
is a multithreaded component. Accessing the UI directly from within itsOnConnect
event (orOnDisconnect
,OnExecute
, orOnException
) is not thread-safe! You need to use Indy'sTIdSync
orTIdNotify
class to access the UI safely.To answer the original question, the simpliest, but not necessarily the safest, way is to store the
TIdContext.Connection
object pointer in theTListItem.Data
property. The main thread code will then have direct access to the connection when it needs it.I do not advise that, though. A safer solution is to uniquely identify each client yourself, such as with a username that the client sends, and store that ID in the
TIdContext.Data
andTListItem.Data
properties. Then, when your main thread code wants to send a message to a client, it can loop through theTIdTCPServer.Contexts
list looking for the desired ID, and if found then it will have access to the correspondingTIdContext.Connection
object.使用:
要获得更多选项,只需在 IOHandler 之后调用代码完成(CTRL+SPACE)并查看可用选项,前段时间,我编写了一个简单的客户端/服务器测试应用程序,单击 此处 查看和/或下载源代码。
use:
For more options, just invoke the code completion(CTRL+SPACE) after IOHandler and see available options, some time ago, I've wrote a simple client/server test app, click here to see and/or download source.