I learned some codes to make a mini HTTP server in MMA way here.
server=SocketListen[8000,Function[{assoc},Block[{client=assoc["SourceSocket"]},
Block[{html,expr},
expr=First@StringCases[assoc["Data"],RegularExpression["GET /\\?expr=([^ ]+)"]->"$1"];
html=ToString@InputForm@ToExpression@URLDecode@expr;
WriteString[client,"HTTP/1.1 200 OK\r\nDate: "<>DateString[]<>"\r\nContent-Type: text/html\r\nContent-Length: "<>
ToString@StringLength@html<>"\n\n"<>html];
Close[client]]]]]
do not forget to close it when finished.
DeleteObject[server]
Close[server["Socket"]]
by the upper codes, we could pass exprs to MMA and get results in TEXTs way, I want to know how to show the Plots or Graphics with these codes in web browsers like Chrome? I wonder that, MMA could be used as web server, there should be some frameworks to help this becoming true, like Express upon node.js. is this worth to do sth? 
Answer
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.


Comments
Post a Comment