Dart中的客户端服务器
我在Dart的客户端/服务器上找到了一些很好的教程。客户端只是通过指定端口上的本地主机向服务器发送请求,服务器只是响应一个字符串。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);
});
}
我还没有实现客户端,但它必须要进行客户端?浏览器不够客户端吗?
此外,我需要做些什么来使服务器提供图像?
要正确提供图片,您需要设置Content-Type标头。除此之外,您拥有的代码正朝着正确的方向发展,因为它已经可以提供文件。另一方面,使用Apache或Nginx可能更容易,然后为Dart服务器设置反向代理。这样Apache或Nginx可以为你提供静态文件。对不起,我们还没有记录所有这些。我也想知道使用Heroku是否适合你。
感谢您的回复。 我已经做了一个html页面,但它不会真的说 。这会引用单个图像,但我希望显示服务器上的所有图像。这是否意味着我必须为每个图像动态创建一个带有'img src =“”'的div/span? 没有为我的整个HTML网页代码没有空间,但它大致是这样的:
Excercise4
这与Dart中的相同,因为它一般在HTML中。您必须为每个图像使用标签。这只是当你使用Apache等。,那些Web服务器可以为你生成这些HTML页面。如果你真的想坚持使用Dart服务器,你应该编写一些代码来循环目录中的图像,并为每个图像生成一个带有标签的HTML页面。 –
我已经粘贴了你的代码(并且稍微修改了一下,我认为这里有几个拼写错误),它确实为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(".");
}
那么你想显示一个图像文件名或图像本身的列表?对于后者,你需要做一些HTML模板。 – tjameson