如何在控制台应用程序中使用TIdUDPServer? [英] How can I use TIdUDPServer in a console application?

查看:112
本文介绍了如何在控制台应用程序中使用TIdUDPServer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Indy UDP服务器组件似乎依赖于Windows消息,因为我看到只有在鼠标光标移到包含服务器组件的表单上时才会出现新消息。

The Indy UDP server component seems to depend on Windows messages, as I see new messages appear only when the mouse cursor moves over the form which contains the server component.

我在运行时使用以下代码创建了该组件:

I created the component at run time using this code:

private
    { Private declarations }
    Srv: TIdUDPServer;
...
procedure TForm1.FormCreate(Sender: TObject);
begin
  Srv := TIdUDPServer.Create(Self);
  Srv.DefaultPort := 9009;
  Srv.OnUDPRead := Self.udpServerUDPRead;
  Srv.Active := True;
end;

我希望使用控制台或服务应用程序。我是否需要一个(不可见的)窗口句柄和一些Windows消息队列代码来使该组件正常工作?

I would prefer a console or service application. Do I need an (invisible) window handle + some windows message queue code which to get this component working?

更新:一些(非正式)文档说:

Update: some (inofficial) documentation says:


TIdUDPServer当处于活动状态时,将创建一个侦听线程来侦听
入站UDP数据包。 ...当ThreadedEvent为false时,将在主程序线程的上下文中触发OnUDPRead
事件。当
ThreadedEvent为true时,将在侦听器线程
的上下文中触发OnUDPRead事件。

TIdUDPServer when active creates a listening thread to listen for inbound UDP packets. ... When ThreadedEvent is false, the OnUDPRead event will be fired in the context of the main program thread. When ThreadedEvent is true, the OnUDPRead event is fired in the context of the listener thread.


推荐答案

如果使用线程,则不需要Windows消息或表单。只需将ThreadedEvent设置为true并在线程中进行处理,请记住该事件即将在另一个线程上发生,因此您将不得不处理线程同步。我仅通过使用处理其自身内部队列(我的消息和我的队列,而不是Windows消息或队列)之外的消息的线程来执行此操作,因此事件处理程序将带有接收到的数据的消息放入线程的队列中,以在目标线程的上下文,而不是Indy侦听器线程。

If you use threading then you don't need Windows messages nor forms. Just set ThreadedEvent to true and handle in a thread, remembering that the event is coming in on a different thread so you will have to handle thread "synchronisation". I do this by only using threads that process messages off their own internal queue (my messages and my queue, not Windows messages or queues), so the event handler puts a message with the received data onto the thread's queue, to be processed in the context of the "destination" thread, not the Indy listener thread.

这篇关于如何在控制台应用程序中使用TIdUDPServer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆