Dart中的客户端服务器

Aom*_*Set 5 client-server dart

我在Dart的客户端/服务器上找到了一些很好的教程.客户端只是通过指定端口上的localhost向服务器发出请求,服务器只响应一个String.

但是,我没有找到任何有关如何提供图像的帮助.我希望能够将服务器映射到客户端的服务器.例如,如果客户端执行类似:localhost:1313/Images的请求,则服务器应响应显示"images"文件夹中所有图像的页面.

这是我到目前为止的代码:

import 'dart:io';

class Server {

_send404(HttpResponse res){
  res.statusCode = HttpStatus.NOT_FOUND;
  res.outputStream.close();
}


void startServer(String mainPath){
HttpServer server = new HttpServer();
server.listen('localhost', 1111);
print("Server listening on localhost, port 1111");

server.defaultRequestHandler = (var req, var res) {
  final String path = req.path == '/' ? '/index.html' : req.path;
  final File file = new File('${mainPath}${path}');

  file.exists().then((bool found) {
    if(found) {
      file.fullPath().then((String fullPath) {
        if(!fullPath.startsWith(mainPath)) {              
          _send404(res);
        } else {
          file.openInputStream().pipe(res.outputStream);
        }
      });
    } else {
        _send404(res);
    }
  });
};


void main(){
Server server = new Server();
File f = new File(new Options().script);
f.directory().then((Directory directory) {
 server.startServer(directory.path);
});
}
Run Code Online (Sandbox Code Playgroud)

我还没有实现客户端,但是有必要实现客户端吗?浏览器不足以作为客户端吗?

另外,我需要做些什么来使服务器提供图像?

Chr*_*ett 5

我已经粘贴了你的代码(并且稍微编辑了一下,我认为有一些拼写错误),并且它确实以chrome形式提供图像 - 目前,你必须传递图像的完整网址,例如: http://localhost:1111/images/foo.png

要获得一个充满图像的页面,您需要编写一个html页面,例如:

<html><body>
   <img src="http://localhost:1111/images/foo.png"/>
   <img src="http://localhost:1111/images/bar.png"/>
</body></html>
Run Code Online (Sandbox Code Playgroud)

并且没有理由不能在服务器上动态创建html,例如,响应images.html对例如一个文件的请求.看一下DirectoryLister该类来迭代服务器端的文件和文件夹.

此外,JJ的评论也是正确的 - 你还应该添加正确的标题,(虽然chrome似乎非常擅长解释没有正确标题的东西).

作为参考,这里的服务器端代码对我来说很好(只是为了我可以测试它... - 删除404和选项 - 它从当前(即应用程序自己的)文件夹提供).

import 'dart:io';

void startServer(String mainPath){
  HttpServer server = new HttpServer();
  server.listen('127.0.0.1', 1111);
  print("Server listening on localhost, port 1111");

  server.defaultRequestHandler = (var req, var res) {
    final String path = req.path == '/' ? '/index.html' : req.path;
    final File file = new File('${mainPath}${path}');

    file.exists().then((bool found) {
      if(found) {
        file.fullPath().then((String fullPath) {
          file.openInputStream().pipe(res.outputStream);
        });
      }
    });      
  };
}

main(){
   startServer(".");  
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*ens 1

要正确提供图像,您需要设置 Content-Type 标头。除此之外,您拥有的代码正在朝着正确的方向发展,因为它已经可以提供文件服务。另一方面,使用 Apache 或 Nginx 然后设置 Dart 服务器的反向代理可能会更容易。这样 Apache 或 Nginx 就可以为您提供静态文件。抱歉,我们还没有记录所有这些内容。我还想知道使用 Heroku 是否适合您。