简体   繁体   English

Delphi Indy将流发送到客户端

[英]Delphi indy send stream to client

I am new with indy servers and so I'm struggling for this simple task. 我是Indy服务器的新手,所以我正在为这个简单的任务而苦苦挣扎。 I have to create a server and upload a little file; 我必须创建一个服务器并上传一个小文件; its size is always 128 bytes. 它的大小始终为128个字节。 Then when someone opens the homepage of the server the file is sent automatically. 然后,当有人打开服务器的主页时,文件将自动发送。 So: 所以:

  1. Upload a file (the one that is 128 bytes) on the disk 在磁盘上载一个文件(一个128字节的文件)
  2. Open a browser like Firefox 打开类似Firefox的浏览器
  3. Type the url (below you can see that I've set 127.0.0.1:798) and when you press enter there is a white page but a dialog appears asking you to download the file. 输入网址(在下面,您可以看到我已经设置了127.0.0.1:798),当您按Enter键时,会出现一个白色页面,但是会出现一个对话框,要求您下载文件。

I have written this code so far: 到目前为止,我已经编写了以下代码:

procedure TForm1.Button1Click(Sender: TObject);
begin

 // IP = 127.0.0.1:798 (port is 798)
 IdTCPServer1.Active := true;
 Memo1.Lines.Add('Server started at: ' + TimeToStr(Now) + slinebreak);

end;

procedure TForm1.Button2Click(Sender: TObject);
begin

 IdTCPServer1.Active := false;
 Memo1.Lines.Add('Server stopped at: ' + TimeToStr(Now));

end;

procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var a: TFileStream;

begin

  a := TFileStream.Create('C:\Users\defaulr.user\Desktop\datfile.pkm', fmOpenWrite);
  AContext.Connection.IOHandler.Write(a);

end;

This is the form: 形式如下:

在此处输入图片说明

Start is Button1 and End is Button2 . 开始是Button1 ,结束是Button2 As you can see I am loading in a stream the file and then I try to send it as output when I open the page. 如您所见,我正在流中加载文件,然后在打开页面时尝试将其作为输出发送。 Is this the proper way to do it? 这是正确的方法吗?

Since you are accessing the file via a web browser, you should be using TIdHTTPServer instead of TIdTCPServer : 由于您是通过Web浏览器访问文件的,因此您应该使用TIdHTTPServer而不是TIdTCPServer

procedure TForm1.Button1Click(Sender: TObject);
begin
  // IP = 127.0.0.1:798 (port is 798)
  IdHTTPServer1.Active := true;
  Memo1.Lines.Add('Server started at: ' + TimeToStr(Now));
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  IdHTTPServer1.Active := false;
  Memo1.Lines.Add('Server stopped at: ' + TimeToStr(Now));
end;

// TIdHTTPServer.OnCommandGet event handler...
procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  if ARequestInfo.Document = '/' then
  begin
    AResponseInfo.ResponseNo := 200;
    AResponseInfo.ServeFile(AContext, 'C:\Users\defaulr.user\Desktop\datfile.pkm');
    // alternatively:
    // AResponseInfo.SmartServeFile(AContext, ARequestInfo, 'C:\Users\defaulr.user\Desktop\datfile.pkm');
  end else
    AResponseInfo.ResponseNo := 404;
end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM