using System; using System.Collections.Generic; using System.Net; using System.Text; using AllocsFixes.JSON; using System.IO; using System.Net.Sockets; using System.Threading; namespace AllocsFixes.NetConnections.Servers.Web { public class WebCommandResult : IConsoleConnection { public static int handlingCount = 0; public static int currentHandlers = 0; public static long totalHandlingTime = 0; private HttpListenerResponse response; private string command; private string parameters; public WebCommandResult (string _command, string _parameters, HttpListenerResponse _response) { Interlocked.Increment (ref handlingCount); Interlocked.Increment (ref currentHandlers); response = _response; command = _command; parameters = _parameters; } public void SendLines (List _output) { MicroStopwatch msw = new MicroStopwatch (); StringBuilder sb = new StringBuilder (); foreach (string line in _output) { sb.AppendLine (line); } JSONObject result = new JSONObject (); result.Add ("command", new JSONString (command)); result.Add ("parameters", new JSONString (parameters)); result.Add ("result", new JSONString (sb.ToString ())); response.SendChunked = false; try { WriteJSON (response, result); } catch (IOException e) { if (e.InnerException is SocketException) { Log.Out ("Error in WebCommandResult.SendLines(): Remote host closed connection: " + e.InnerException.Message); } else { Log.Out ("Error (IO) in WebCommandResult.SendLines(): " + e); } } catch (Exception e) { Log.Out ("Error in WebCommandResult.SendLines(): " + e); } finally { if (response != null) { response.Close (); } msw.Stop (); totalHandlingTime += msw.ElapsedMicroseconds; Log.Out ("WebCommandResult.SendLines(): Took {0} µs", msw.ElapsedMicroseconds); Interlocked.Decrement (ref currentHandlers); } } public void WriteJSON (HttpListenerResponse resp, JSON.JSONNode root) { byte[] buf = Encoding.UTF8.GetBytes (root.ToString()); resp.ContentLength64 = buf.Length; resp.ContentType = "application/json"; resp.ContentEncoding = Encoding.UTF8; resp.OutputStream.Write (buf, 0, buf.Length); } public void SendLine (string _text) { //throw new NotImplementedException (); } public void SendLog (string _msg, string _trace, UnityEngine.LogType _type) { //throw new NotImplementedException (); } public void EnableLogLevel (UnityEngine.LogType _type, bool _enable) { //throw new NotImplementedException (); } public string GetDescription () { return "WebCommandResult_for_" + command; } } }