首页 文章

Dart 中的客户端服务器

提问于
浏览
5

我在 Dart 的 client/server 找到了一些很好的教程。客户端只是通过指定端口上的 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);
});
}

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

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

2 回答

  • 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>
    

    并且没有理由不能在服务器上动态创建 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(".");  
    }
    
  • 1

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

相关问题