source: binary-improvements/MapRendering/Web/WebCommandResult.cs@ 281

Last change on this file since 281 was 279, checked in by alloc, 8 years ago

Mod stuff

File size: 2.6 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Net;
4using System.Text;
5
6using AllocsFixes.JSON;
7using System.IO;
8using System.Net.Sockets;
9using System.Threading;
10
11namespace AllocsFixes.NetConnections.Servers.Web
12{
13 public class WebCommandResult : IConsoleConnection
14 {
15 public static int handlingCount = 0;
16 public static int currentHandlers = 0;
17 public static long totalHandlingTime = 0;
18
19 private HttpListenerResponse response;
20 private string command;
21 private string parameters;
22
23 public WebCommandResult (string _command, string _parameters, HttpListenerResponse _response) {
24 Interlocked.Increment (ref handlingCount);
25 Interlocked.Increment (ref currentHandlers);
26
27 response = _response;
28 command = _command;
29 parameters = _parameters;
30 }
31
32 public void SendLines (List<string> _output) {
33 MicroStopwatch msw = new MicroStopwatch ();
34
35 StringBuilder sb = new StringBuilder ();
36 foreach (string line in _output) {
37 sb.AppendLine (line);
38 }
39
40 JSONObject result = new JSONObject ();
41
42 result.Add ("command", new JSONString (command));
43 result.Add ("parameters", new JSONString (parameters));
44 result.Add ("result", new JSONString (sb.ToString ()));
45
46 response.SendChunked = false;
47
48 try {
49 WriteJSON (response, result);
50 } catch (IOException e) {
51 if (e.InnerException is SocketException) {
52 Log.Out ("Error in WebCommandResult.SendLines(): Remote host closed connection: " + e.InnerException.Message);
53 } else {
54 Log.Out ("Error (IO) in WebCommandResult.SendLines(): " + e);
55 }
56 } catch (Exception e) {
57 Log.Out ("Error in WebCommandResult.SendLines(): " + e);
58 } finally {
59 if (response != null) {
60 response.Close ();
61 }
62
63 msw.Stop ();
64 totalHandlingTime += msw.ElapsedMicroseconds;
65 Log.Out ("WebCommandResult.SendLines(): Took {0} µs", msw.ElapsedMicroseconds);
66 Interlocked.Decrement (ref currentHandlers);
67 }
68 }
69
70 public void WriteJSON (HttpListenerResponse resp, JSON.JSONNode root)
71 {
72 byte[] buf = Encoding.UTF8.GetBytes (root.ToString());
73 resp.ContentLength64 = buf.Length;
74 resp.ContentType = "application/json";
75 resp.ContentEncoding = Encoding.UTF8;
76 resp.OutputStream.Write (buf, 0, buf.Length);
77 }
78
79 public void SendLine (string _text) {
80 //throw new NotImplementedException ();
81 }
82
83 public void SendLog (string _msg, string _trace, UnityEngine.LogType _type) {
84 //throw new NotImplementedException ();
85 }
86
87 public void EnableLogLevel (UnityEngine.LogType _type, bool _enable) {
88 //throw new NotImplementedException ();
89 }
90
91 public string GetDescription () {
92 return "WebCommandResult_for_" + command;
93 }
94 }
95}
96
Note: See TracBrowser for help on using the repository browser.