且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Delphi中发送和接收数据流

更新时间:2022-11-28 12:38:11

我建议使用UDP协议并将时间戳信息添加到数据中并跟踪传入接收端的数据。您可以使用Indy或其他软件包中的UDP服务器(TIdUDPServer)和客户端(TIdUDPClient)组件。客户端组件用于发送数据,服务器用于接收。

I suggest using UDP protocol and adding timestamp information to your data and track incoming data on the receiving end. You can use UDP server (TIdUDPServer) and client (TIdUDPClient) components from Indy or other packages. Client component is for sending data and server for receiving.

我个人通常更喜欢突触-类。它们的级别比Indy低,因此更容易知道发生了什么,但另一方面,您可能需要自己实现Indy默认提供的功能。

Personally I usually prefer Synapse -classes. They are lower level than Indy, so it's easier to know what's happening but on the otherhand you may need to implement something yourself what Indy may provide by default.

更新

实施非常简单:

发送数据:

将TIdUDPClient拖放到窗体上。将主机设置为接收端的名称或IP地址(如果在同一台计算机上运行程序,则设置为 localhost),将端口设置为服务器正在侦听的高编号,例如54656。

Drop TIdUDPClient on the form. Set "Host" to name or IP address of receiving end (or "localhost" if you run your programs in same computer) and port to high number where server is listening, eg 54656.

向按钮或计时器事件添加以下代码:

Add following code to button or timer event:

IdUDPClient1.Send('Hello, world!');

接收数据:

Drop TIdUDPServer组件在表格上。将默认端口设置为与发送应用程序相同的端口。添加OnUDPRead事件处理程序,代码如下:

Drop TIdUDPServer component on the form. Set default port to same port as in sending application. Add OnUDPRead event handler, with code:

MessageDlg('Received: ' + StringOf(AData), mtInformation, [mbOk], 0);

每次收到新消息时都会弹出新消息对话框。

And new message dialog pops up everytime new message is received.

更新2

UDP对于图像不是很好,如果要确保它们不会损坏,除非图片非常小,可以放入一个小包。

UDP is not good for images, if you want to be sure they will stay uncorrupted, unless the image is very small and fits inside one packet.