How to show Plots or Graphics in mini MMA HTTP Server?
Very often SVG makes sense, it will scale well with magnification. This idea does not deserve a separate answer so additionally I rewrote the code in a more idiomatic style:
server = SocketListen[8000
, Function[{assoc}
, Module[
{ client = assoc["SourceSocket"], inputString, response}
, inputString = ImportString[assoc["Data"], "HTTPRequest"] @ "Query" // Lookup["expr"]
; response = GenerateHTTPResponse @ ExportForm[
ToExpression[inputString], "SVG"
]
; WriteString[client, ExportString[response, "HTTPResponse"]]
; Close @ client
]
]
]
(* DeleteObject[server]
Close[server["Socket"]]
*)
You can get it to respond with images by doing the following:
server = SocketListen[8000,
Function[{assoc},
Block[{client = assoc["SourceSocket"]},
Block[{html, expr},
expr = First@
StringCases[assoc["Data"],
RegularExpression["GET /\\?expr=([^ ]+)"] -> "$1"];
response = ExportString[ToExpression@URLDecode@expr, "PNG"];
WriteString[client,
"HTTP/1.1 200 OK\r\nDate: " <> DateString[] <>
"\r\nContent-Type: image/png\r\nContent-Length: " <>
ToString@StringLength@response <> "\n\n" <> response];
Close[client]]]]]
I've made 2 changes - first is to change the response Content-Type to image/png
. Otherwise the browser doesn't know the response is an image.
Next I used ExportString[..., "PNG]
to get MMA to respond with the string representation of an image, which, when coupled with the Content-Type change, will render correctly in a browser, as below.
To your broader question - in my opinion, to make this a real-live web server is a ton of work and probably not worth it when CloudDeploy
and family exist.