Changed the source formatting of the HttpServer class to match the rest of the project.

This commit is contained in:
Michael Möller
2012-10-28 14:06:50 +00:00
parent 87641aebbd
commit 69b0050008
2 changed files with 322 additions and 356 deletions

View File

@@ -267,9 +267,9 @@ namespace OpenHardwareMonitor.GUI {
runWebServerMenuItem, settings); runWebServerMenuItem, settings);
runWebServer.Changed += delegate(object sender, EventArgs e) { runWebServer.Changed += delegate(object sender, EventArgs e) {
if (runWebServer.Value) if (runWebServer.Value)
runWebServer.Value = server.startHTTPListener(); runWebServer.Value = server.StartHTTPListener();
else else
server.stopHTTPListener(); server.StopHTTPListener();
}; };
InitializePlotForm(); InitializePlotForm();

View File

@@ -5,43 +5,40 @@
file, You can obtain one at http://mozilla.org/MPL/2.0/. file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (C) 2012 Prince Samuel <prince.samuel@gmail.com> Copyright (C) 2012 Prince Samuel <prince.samuel@gmail.com>
Copyright (C) 2012 Michael Möller <mmoeller@openhardwaremonitor.org>
*/ */
using System; using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
using OpenHardwareMonitor.GUI;
using OpenHardwareMonitor.Hardware;
using System.Reflection;
using System.Drawing; using System.Drawing;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using OpenHardwareMonitor.GUI;
using OpenHardwareMonitor.Hardware;
namespace OpenHardwareMonitor.Utilities namespace OpenHardwareMonitor.Utilities {
{
public class HttpServer public class HttpServer {
{
private HttpListener listener; private HttpListener listener;
private int listenerPort, nodeCount; private int listenerPort, nodeCount;
private Thread listenerThread; private Thread listenerThread;
private Node root; private Node root;
public HttpServer(Node r, int p) public HttpServer(Node r, int p) {
{
root = r; root = r;
listenerPort = p; listenerPort = p;
//JSON node count. //JSON node count.
nodeCount = 0; nodeCount = 0;
listener = new HttpListener(); listener = new HttpListener();
} }
public Boolean startHTTPListener() public Boolean StartHTTPListener() {
{ try {
try
{
if (listener.IsListening) if (listener.IsListening)
return true; return true;
@@ -50,55 +47,40 @@ namespace OpenHardwareMonitor.Utilities
listener.Prefixes.Add(prefix); listener.Prefixes.Add(prefix);
listener.Start(); listener.Start();
if (listenerThread == null) if (listenerThread == null) {
{
listenerThread = new Thread(HandleRequests); listenerThread = new Thread(HandleRequests);
listenerThread.Start(); listenerThread.Start();
} }
} } catch (Exception) {
catch (Exception e)
{
return false; return false;
} }
return true; return true;
} }
public Boolean stopHTTPListener() public Boolean StopHTTPListener() {
{ try {
try
{
listenerThread.Abort(); listenerThread.Abort();
listener.Stop(); listener.Stop();
listenerThread = null; listenerThread = null;
} } catch (HttpListenerException) {
catch (System.Net.HttpListenerException e) } catch (ThreadAbortException) {
{ } catch (NullReferenceException) {
} } catch (Exception) {
catch (System.Threading.ThreadAbortException e)
{
}
catch (System.NullReferenceException e)
{
}
catch (Exception e)
{
} }
return true; return true;
} }
public void HandleRequests() public void HandleRequests() {
{
while (listener.IsListening) while (listener.IsListening) {
{ var context = listener.BeginGetContext(
var context = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); new AsyncCallback(ListenerCallback), listener);
context.AsyncWaitHandle.WaitOne(); context.AsyncWaitHandle.WaitOne();
} }
} }
public void ListenerCallback(IAsyncResult result) public void ListenerCallback(IAsyncResult result) {
{
HttpListener listener = (HttpListener)result.AsyncState; HttpListener listener = (HttpListener)result.AsyncState;
if (listener == null || !listener.IsListening) if (listener == null || !listener.IsListening)
return; return;
@@ -107,31 +89,32 @@ namespace OpenHardwareMonitor.Utilities
HttpListenerRequest request = context.Request; HttpListenerRequest request = context.Request;
var requestedFile = request.RawUrl.Substring(1); var requestedFile = request.RawUrl.Substring(1);
if (requestedFile == "data.json") if (requestedFile == "data.json") {
{ SendJSON(context);
sendJSON(context);
return; return;
} }
if (requestedFile.Contains("images_icon")) if (requestedFile.Contains("images_icon")) {
{ ServeResourceImage(context, requestedFile.Replace("images_icon/", ""));
serveResourceImage(context, requestedFile.Replace("images_icon/", ""));
return; return;
} }
//default file to be served // default file to be served
if (string.IsNullOrEmpty(requestedFile)) if (string.IsNullOrEmpty(requestedFile))
requestedFile = "index.html"; requestedFile = "index.html";
string[] splits = requestedFile.Split('.'); string[] splits = requestedFile.Split('.');
string ext = splits[splits.Length - 1]; string ext = splits[splits.Length - 1];
serveResourceFile(context, "Web." + requestedFile.Replace('/', '.'), ext); ServeResourceFile(context, "Web." + requestedFile.Replace('/', '.'), ext);
} }
private void serveResourceFile(HttpListenerContext context ,string name, string ext) { private void ServeResourceFile(HttpListenerContext context, string name,
string ext)
{
//hack! resource names do not support the hyphen // resource names do not support the hyphen
name = "OpenHardwareMonitor.Resources." + name.Replace("custom-theme", "custom_theme"); name = "OpenHardwareMonitor.Resources." +
name.Replace("custom-theme", "custom_theme");
string[] names = string[] names =
Assembly.GetExecutingAssembly().GetManifestResourceNames(); Assembly.GetExecutingAssembly().GetManifestResourceNames();
@@ -139,12 +122,11 @@ namespace OpenHardwareMonitor.Utilities
if (names[i].Replace('\\', '.') == name) { if (names[i].Replace('\\', '.') == name) {
using (Stream stream = Assembly.GetExecutingAssembly(). using (Stream stream = Assembly.GetExecutingAssembly().
GetManifestResourceStream(names[i])) { GetManifestResourceStream(names[i])) {
context.Response.ContentType = getcontentType("." + ext); context.Response.ContentType = GetcontentType("." + ext);
context.Response.ContentLength64 = stream.Length; context.Response.ContentLength64 = stream.Length;
byte[] buffer = new byte[512 * 1024]; byte[] buffer = new byte[512 * 1024];
int len; int len;
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) {
{
context.Response.OutputStream.Write(buffer, 0, len); context.Response.OutputStream.Write(buffer, 0, len);
} }
context.Response.OutputStream.Close(); context.Response.OutputStream.Close();
@@ -157,7 +139,7 @@ namespace OpenHardwareMonitor.Utilities
context.Response.Close(); context.Response.Close();
} }
private void serveResourceImage(HttpListenerContext context ,string name) { private void ServeResourceImage(HttpListenerContext context, string name) {
name = "OpenHardwareMonitor.Resources." + name; name = "OpenHardwareMonitor.Resources." + name;
string[] names = string[] names =
@@ -169,8 +151,7 @@ namespace OpenHardwareMonitor.Utilities
Image image = Image.FromStream(stream); Image image = Image.FromStream(stream);
context.Response.ContentType = "image/png"; context.Response.ContentType = "image/png";
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream()) {
{
image.Save(ms, ImageFormat.Png); image.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream); ms.WriteTo(context.Response.OutputStream);
} }
@@ -185,12 +166,11 @@ namespace OpenHardwareMonitor.Utilities
context.Response.Close(); context.Response.Close();
} }
private void sendJSON(HttpListenerContext context) private void SendJSON(HttpListenerContext context) {
{
string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": ["; string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": [";
nodeCount = 1; nodeCount = 1;
JSON += generateJSON(root); JSON += GenerateJSON(root);
JSON += "]"; JSON += "]";
JSON += ", \"Min\": \"Min\""; JSON += ", \"Min\": \"Min\"";
JSON += ", \"Value\": \"Value\""; JSON += ", \"Value\": \"Value\"";
@@ -210,40 +190,35 @@ namespace OpenHardwareMonitor.Utilities
} }
private string generateJSON(Node n) private string GenerateJSON(Node n) {
{ string JSON = "{\"id\": " + nodeCount + ", \"Text\": \"" + n.Text
string JSON = "{\"id\": " + nodeCount + ", \"Text\": \"" + n.Text + "\", \"Children\": ["; + "\", \"Children\": [";
nodeCount++; nodeCount++;
foreach (Node child in n.Nodes) foreach (Node child in n.Nodes)
JSON += generateJSON(child) + ", "; JSON += GenerateJSON(child) + ", ";
if (JSON.EndsWith(", ")) if (JSON.EndsWith(", "))
JSON = JSON.Remove(JSON.LastIndexOf(",")); JSON = JSON.Remove(JSON.LastIndexOf(","));
JSON += "]"; JSON += "]";
if (n is SensorNode) if (n is SensorNode) {
{
JSON += ", \"Min\": \"" + ((SensorNode)n).Min + "\""; JSON += ", \"Min\": \"" + ((SensorNode)n).Min + "\"";
JSON += ", \"Value\": \"" + ((SensorNode)n).Value + "\""; JSON += ", \"Value\": \"" + ((SensorNode)n).Value + "\"";
JSON += ", \"Max\": \"" + ((SensorNode)n).Max + "\""; JSON += ", \"Max\": \"" + ((SensorNode)n).Max + "\"";
JSON += ", \"ImageURL\": \"images/transparent.png\""; JSON += ", \"ImageURL\": \"images/transparent.png\"";
} } else if (n is HardwareNode) {
else if (n is HardwareNode)
{
JSON += ", \"Min\": \"\""; JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\""; JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\""; JSON += ", \"Max\": \"\"";
JSON += ", \"ImageURL\": \"images_icon/" + getHardwareImageFile((HardwareNode)n) + "\""; JSON += ", \"ImageURL\": \"images_icon/" +
} GetHardwareImageFile((HardwareNode)n) + "\"";
else if (n is TypeNode) } else if (n is TypeNode) {
{
JSON += ", \"Min\": \"\""; JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\""; JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\""; JSON += ", \"Max\": \"\"";
JSON += ", \"ImageURL\": \"images_icon/" + getTypeImageFile((TypeNode)n) + "\""; JSON += ", \"ImageURL\": \"images_icon/" +
} GetTypeImageFile((TypeNode)n) + "\"";
else } else {
{
JSON += ", \"Min\": \"\""; JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\""; JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\""; JSON += ", \"Max\": \"\"";
@@ -254,13 +229,13 @@ namespace OpenHardwareMonitor.Utilities
return JSON; return JSON;
} }
private static void returnFile(HttpListenerContext context, string filePath) private static void ReturnFile(HttpListenerContext context, string filePath)
{ {
context.Response.ContentType = getcontentType(Path.GetExtension(filePath)); context.Response.ContentType =
GetcontentType(Path.GetExtension(filePath));
const int bufferSize = 1024 * 512; //512KB const int bufferSize = 1024 * 512; //512KB
var buffer = new byte[bufferSize]; var buffer = new byte[bufferSize];
using (var fs = File.OpenRead(filePath)) using (var fs = File.OpenRead(filePath)) {
{
context.Response.ContentLength64 = fs.Length; context.Response.ContentLength64 = fs.Length;
int read; int read;
@@ -271,10 +246,8 @@ namespace OpenHardwareMonitor.Utilities
context.Response.OutputStream.Close(); context.Response.OutputStream.Close();
} }
private static string getcontentType(string extension) private static string GetcontentType(string extension) {
{ switch (extension) {
switch (extension)
{
case ".avi": return "video/x-msvideo"; case ".avi": return "video/x-msvideo";
case ".css": return "text/css"; case ".css": return "text/css";
case ".doc": return "application/msword"; case ".doc": return "application/msword";
@@ -294,11 +267,9 @@ namespace OpenHardwareMonitor.Utilities
} }
} }
private static string getHardwareImageFile(HardwareNode hn) private static string GetHardwareImageFile(HardwareNode hn) {
{
switch (hn.Hardware.HardwareType) switch (hn.Hardware.HardwareType) {
{
case HardwareType.CPU: case HardwareType.CPU:
return "cpu.png"; return "cpu.png";
case HardwareType.GpuNvidia: case HardwareType.GpuNvidia:
@@ -323,11 +294,9 @@ namespace OpenHardwareMonitor.Utilities
} }
private static string getTypeImageFile(TypeNode tn) private static string GetTypeImageFile(TypeNode tn) {
{
switch (tn.SensorType) switch (tn.SensorType) {
{
case SensorType.Voltage: case SensorType.Voltage:
return "voltage.png"; return "voltage.png";
case SensorType.Clock: case SensorType.Clock:
@@ -352,21 +321,18 @@ namespace OpenHardwareMonitor.Utilities
} }
public int ListenerPort public int ListenerPort {
{
get { return listenerPort; } get { return listenerPort; }
set { listenerPort = value; } set { listenerPort = value; }
} }
~HttpServer() ~HttpServer() {
{ StopHTTPListener();
stopHTTPListener();
listener.Abort(); listener.Abort();
} }
public void Quit() public void Quit() {
{ StopHTTPListener();
stopHTTPListener();
listener.Abort(); listener.Abort();
} }
} }