我在 Dart 的客户端/服务器上找到了一些不错的教程。客户端只是通过本地主机在指定端口上向服务器发出请求,服务器只用一个字符串响应。
但是,我没有找到有关如何提供图像的任何帮助。我希望能够让服务器到服务器图像到客户端。例如,如果客户端执行如下请求:
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);
});
}
我还没有实现客户端,但是有必要实现一个客户端吗?浏览器作为客户端还不够吗?
另外,我需要做什么才能使服务器提供图像?
最佳答案
我已经粘贴了您的代码(并对其进行了轻微编辑,我认为有几个错别字),并且它确实提供了 chrome 中的图像 - 目前,您必须传递图像的完整 url,例如: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(".");
}
关于client-server - Dart 中的客户端服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13843362/