Utilities/HttpServer.cs
changeset 387 87093432c843
parent 386 7094d5dd924b
     1.1 --- a/Utilities/HttpServer.cs	Sun Oct 28 14:06:50 2012 +0000
     1.2 +++ b/Utilities/HttpServer.cs	Sun Oct 28 15:19:45 2012 +0000
     1.3 @@ -28,16 +28,30 @@
     1.4      private Thread listenerThread;
     1.5      private Node root;
     1.6  
     1.7 -    public HttpServer(Node r, int p) {
     1.8 -      root = r;
     1.9 -      listenerPort = p;
    1.10 +    public HttpServer(Node node, int port) {
    1.11 +      root = node;
    1.12 +      listenerPort = port;
    1.13  
    1.14        //JSON node count. 
    1.15        nodeCount = 0;
    1.16 -      listener = new HttpListener();
    1.17 +
    1.18 +      try {
    1.19 +        listener = new HttpListener();
    1.20 +      } catch (PlatformNotSupportedException) {
    1.21 +        listener = null;
    1.22 +      }
    1.23 +    }
    1.24 +
    1.25 +    public bool PlatformNotSupported {
    1.26 +      get {
    1.27 +        return listener == null;
    1.28 +      }
    1.29      }
    1.30  
    1.31      public Boolean StartHTTPListener() {
    1.32 +      if (PlatformNotSupported)
    1.33 +        return false;
    1.34 +
    1.35        try {
    1.36          if (listener.IsListening)
    1.37            return true;
    1.38 @@ -59,6 +73,9 @@
    1.39      }
    1.40  
    1.41      public Boolean StopHTTPListener() {
    1.42 +      if (PlatformNotSupported)
    1.43 +        return false;
    1.44 +
    1.45        try {
    1.46          listenerThread.Abort();
    1.47          listener.Stop();
    1.48 @@ -71,7 +88,7 @@
    1.49        return true;
    1.50      }
    1.51  
    1.52 -    public void HandleRequests() {
    1.53 +    private void HandleRequests() {
    1.54  
    1.55        while (listener.IsListening) {
    1.56          var context = listener.BeginGetContext(
    1.57 @@ -80,22 +97,30 @@
    1.58        }
    1.59      }
    1.60  
    1.61 -    public void ListenerCallback(IAsyncResult result) {
    1.62 +    private void ListenerCallback(IAsyncResult result) {
    1.63        HttpListener listener = (HttpListener)result.AsyncState;
    1.64        if (listener == null || !listener.IsListening)
    1.65          return;
    1.66 +
    1.67        // Call EndGetContext to complete the asynchronous operation.
    1.68 -      HttpListenerContext context = listener.EndGetContext(result);
    1.69 +      HttpListenerContext context;
    1.70 +      try {
    1.71 +        context = listener.EndGetContext(result);     
    1.72 +      } catch (Exception) {
    1.73 +        return;
    1.74 +      }
    1.75 +
    1.76        HttpListenerRequest request = context.Request;
    1.77  
    1.78        var requestedFile = request.RawUrl.Substring(1);
    1.79        if (requestedFile == "data.json") {
    1.80 -        SendJSON(context);
    1.81 +        SendJSON(context.Response);
    1.82          return;
    1.83        }
    1.84  
    1.85        if (requestedFile.Contains("images_icon")) {
    1.86 -        ServeResourceImage(context, requestedFile.Replace("images_icon/", ""));
    1.87 +        ServeResourceImage(context.Response, 
    1.88 +          requestedFile.Replace("images_icon/", ""));
    1.89          return;
    1.90        }
    1.91  
    1.92 @@ -105,13 +130,13 @@
    1.93  
    1.94        string[] splits = requestedFile.Split('.');
    1.95        string ext = splits[splits.Length - 1];
    1.96 -      ServeResourceFile(context, "Web." + requestedFile.Replace('/', '.'), ext);
    1.97 +      ServeResourceFile(context.Response, 
    1.98 +        "Web." + requestedFile.Replace('/', '.'), ext);
    1.99      }
   1.100  
   1.101 -    private void ServeResourceFile(HttpListenerContext context, string name, 
   1.102 +    private void ServeResourceFile(HttpListenerResponse response, string name, 
   1.103        string ext) 
   1.104      {
   1.105 -
   1.106        // resource names do not support the hyphen
   1.107        name = "OpenHardwareMonitor.Resources." + 
   1.108          name.Replace("custom-theme", "custom_theme");
   1.109 @@ -122,24 +147,29 @@
   1.110          if (names[i].Replace('\\', '.') == name) {
   1.111            using (Stream stream = Assembly.GetExecutingAssembly().
   1.112              GetManifestResourceStream(names[i])) {
   1.113 -            context.Response.ContentType = GetcontentType("." + ext);
   1.114 -            context.Response.ContentLength64 = stream.Length;
   1.115 +            response.ContentType = GetcontentType("." + ext);
   1.116 +            response.ContentLength64 = stream.Length;
   1.117              byte[] buffer = new byte[512 * 1024];
   1.118              int len;
   1.119 -            while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) {
   1.120 -              context.Response.OutputStream.Write(buffer, 0, len);
   1.121 +            try {
   1.122 +              Stream output = response.OutputStream;
   1.123 +              while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) {
   1.124 +                output.Write(buffer, 0, len);
   1.125 +              }
   1.126 +              output.Close();
   1.127 +            } catch (HttpListenerException) {
   1.128              }
   1.129 -            context.Response.OutputStream.Close();
   1.130 -          }
   1.131 -          return;
   1.132 +            response.Close();
   1.133 +            return;
   1.134 +          }          
   1.135          }
   1.136        }
   1.137 -      context.Response.OutputStream.Close();
   1.138 -      context.Response.StatusCode = 404;
   1.139 -      context.Response.Close();
   1.140 +
   1.141 +      response.StatusCode = 404;
   1.142 +      response.Close();
   1.143      }
   1.144  
   1.145 -    private void ServeResourceImage(HttpListenerContext context, string name) {
   1.146 +    private void ServeResourceImage(HttpListenerResponse response, string name) {
   1.147        name = "OpenHardwareMonitor.Resources." + name;
   1.148  
   1.149        string[] names =
   1.150 @@ -150,23 +180,28 @@
   1.151              GetManifestResourceStream(names[i])) {
   1.152  
   1.153              Image image = Image.FromStream(stream);
   1.154 -            context.Response.ContentType = "image/png";
   1.155 -            using (MemoryStream ms = new MemoryStream()) {
   1.156 -              image.Save(ms, ImageFormat.Png);
   1.157 -              ms.WriteTo(context.Response.OutputStream);
   1.158 +            response.ContentType = "image/png";
   1.159 +            try {
   1.160 +              Stream output = response.OutputStream;
   1.161 +              using (MemoryStream ms = new MemoryStream()) {
   1.162 +                image.Save(ms, ImageFormat.Png);
   1.163 +                ms.WriteTo(output);
   1.164 +              }
   1.165 +              output.Close();
   1.166 +            } catch (HttpListenerException) {              
   1.167              }
   1.168 -            context.Response.OutputStream.Close();
   1.169              image.Dispose();
   1.170 +            response.Close();
   1.171              return;
   1.172            }
   1.173          }
   1.174        }
   1.175 -      context.Response.OutputStream.Close();
   1.176 -      context.Response.StatusCode = 404;
   1.177 -      context.Response.Close();
   1.178 +
   1.179 +      response.StatusCode = 404;
   1.180 +      response.Close();
   1.181      }
   1.182  
   1.183 -    private void SendJSON(HttpListenerContext context) {
   1.184 +    private void SendJSON(HttpListenerResponse response) {
   1.185  
   1.186        string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": [";
   1.187        nodeCount = 1;
   1.188 @@ -181,13 +216,19 @@
   1.189        var responseContent = JSON;
   1.190        byte[] buffer = Encoding.UTF8.GetBytes(responseContent);
   1.191  
   1.192 -      context.Response.ContentLength64 = buffer.Length;
   1.193 -      context.Response.ContentType = "application/json";
   1.194 +      response.AddHeader("Cache-Control", "no-cache");
   1.195  
   1.196 -      Stream outputStream = context.Response.OutputStream;
   1.197 -      outputStream.Write(buffer, 0, buffer.Length);
   1.198 -      outputStream.Close();
   1.199 +      response.ContentLength64 = buffer.Length;
   1.200 +      response.ContentType = "application/json";
   1.201  
   1.202 +      try {
   1.203 +        Stream output = response.OutputStream;
   1.204 +        output.Write(buffer, 0, buffer.Length);
   1.205 +        output.Close();
   1.206 +      } catch (HttpListenerException) {
   1.207 +      }
   1.208 +
   1.209 +      response.Close();
   1.210      }
   1.211  
   1.212      private string GenerateJSON(Node n) {
   1.213 @@ -327,11 +368,17 @@
   1.214      }
   1.215  
   1.216      ~HttpServer() {
   1.217 +      if (PlatformNotSupported)
   1.218 +        return;
   1.219 +
   1.220        StopHTTPListener();
   1.221        listener.Abort();
   1.222      }
   1.223  
   1.224      public void Quit() {
   1.225 +      if (PlatformNotSupported)
   1.226 +        return;
   1.227 +
   1.228        StopHTTPListener();
   1.229        listener.Abort();
   1.230      }