Dart HTML Server。如何让服务器拒绝多个客户端连接?

时间:2014-05-20 23:55:38

标签: webserver dart

我编写的Web应用程序只能由一个客户端使用,并且只想接受一个与服务器的连接。局域网将局限于飞机。我是Dart,HTML等的新手。我如何拒绝与服务器的多个连接?

这里的代码是HTTP服务器 -

class MicroServer {

  var address;
  var port;

  var httpServer;    // global

  MicroServer(this.address, this.port) {
    final HTTP_ROOT_PATH = Platform.script.resolve('../build/web').toFilePath();
    final virDir = new VirtualDirectory(HTTP_ROOT_PATH)
      ..jailRoot = false  
      ..allowDirectoryListing = true;

  HttpServer.bind(address, port)
    .then((httpserver) {
    httpServer = httpserver;
    httpserver.listen((request) {
        virDir.serveRequest(request);
      });
    });
  }

}

2 个答案:

答案 0 :(得分:1)

Dart是单线程的,因此您可以安全地使用检查变量来查看当前连接是否存在:

  bool hasClient = false;

  HttpServer.bind(address, port)
    .then((httpserver) {
    httpServer = httpserver;
    httpserver.listen((request) {
        if (hasClient) {
          sendBusyPage(request);
        } else {
          hasClient = true;
          virDir.serveRequest(request);
          hasClient = false;
        }
      });
    });
  }

答案 1 :(得分:1)

我发现下面的代码到目前为止一直有效。我也可以利用

 if(request.session.isNew) // then grab the session.id etc.

但是使用session.id变量同样容易,因为无论如何我都会使用它。

class MicroServer {

  var address;
  var port;

  var httpServer; 
  var sessionID;  // null until first request received


  MicroServer(this.address, this.port) {
    final HTTP_ROOT_PATH = Platform.script.resolve('../build/web').toFilePath();
    final virDir = new VirtualDirectory(HTTP_ROOT_PATH)
      ..jailRoot = false  // process links will work
      ..followLinks = true
      ..allowDirectoryListing = true;

  HttpServer.bind(address, port)
    .then((httpserver) {
      httpServer = httpserver;
      httpserver.idleTimeout = null;
      print("micro server started on ${httpserver.address}:${httpserver.port}");
      httpserver.listen((request) {
        if(sessionID == null) {
          sessionID = request.session.id;
          virDir.serveRequest(request);
        } else if(sessionID == request.session.id){
          virDir.serveRequest(request);
        } else {
          request.response.writeln('ERROR - Connection is in use.');
          request.response.close();
          request.session.destroy();
        }
      });
    }).catchError((e) => print(e.toString()));
  }

}