-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviz_server.nb
62 lines (46 loc) · 1.84 KB
/
viz_server.nb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
parse[text_String] :=
Module[{output,
json = ImportString[Last@StringSplit[text, "\r\n"], "RawJSON"]},
If[MissingQ@json["data"], json["data"] = <||>];
(* remove underscore in variable names in script *)
json["script"] =
StringReplace[json["script"],
Normal@AssociationMap[StringReplace[#, "_" -> ""] &,
Keys@json["data"]]];
(* remove underscore in variable names *)
json["data"] = KeyMap[StringReplace[#, "_" -> ""] &, json["data"]];
(* set precision for all the real numbers *)
json["data"] =
json["data"] /.
x_Real :> ToString@NumberForm[x, DefaultPrintPrecision -> 20];
output =
ToExpression[
StringRiffle[#, {"With[{", ",", "},"}, "="] &@(List @@@
Normal@json["data"]) <> json["script"] <> "]"];
Return[output];
]
server = SocketListen[38000, Function[{assoc},
Module[{client = assoc["SourceSocket"], imgData, output, data,
evalData},
(* print each request *)
Print[assoc];
(* evaluate script *)
evalData = EvaluationData[data = parse@assoc["Data"];];
(* check whether the evaluation was successful *)
If[Not@evalData["Success"],
data = Column[{Text[Style["Error", 30]],
Column[Rasterize /@
DeleteDuplicates@evalData["MessagesText"]]}]];
imgData =
StringReplace[#, "\n" -> ""] &@
ExportString[
Rasterize[data, RasterSize -> 600], {"Base64", "PNG"}];
output = "HTTP/1.1 200 OK" <>
"\r\nServer: Mathematica/" <> ToString@$VersionNumber <>
"\r\nContent-Type: text/image; charset=utf-8" <>
"\r\nDate: " <> DateString[TimeZone -> 0] <> " GMT" <>
"\r\nContent-Length: " <> ToString@StringLength@imgData <>
"\r\nVary: Accept-Encoding\r\n\r\n" <> imgData;
WriteString[client, output];
]]];
server["Socket"]