I noticed an undocumented socket package (SocketLink
) in Mathematica (Using version 10, not sure when it was actually added) and wrote a barebones HTTP responder using it:
< host = "localhost";
port = 9999;
eol = "\r\n";
helloHTML =
"Hello world! Hello world!";
response = "HTTP/1.1 200 OK"<>eol<>
"Content-length: "<>ToString[StringLength[helloHTML<>eol]]<>eol<>eol<>
helloHTML<>eol;
handler[streams_] := Module[{
inStream = streams[[1]],
outStream = streams[[2]],
req = {},
reqString
},
While[!MatchQ[req, {___, 13, 10, 13, 10}],
AppendTo[req, BinaryRead[inStream]];
];
Close[inStream];
reqString = FromCharacterCode[req];
(* print request *)
Print[reqString];
BinaryWrite[outStream, ToCharacterCode[response]];
Close[outStream];
];
s = CreateServerSocket[port]
ser = CreateAsynchronousServer[s, handler]
The issue is that I have no way of telling when there is no more content in the input stream. This is a problem because if I read once byte beyond this the kernel crashes. I get around it in the above code by reading each character individually and using pattern matching to detect when the request ends (at "\r\n\r\n"):
While[!MatchQ[req, {___, 13, 10, 13, 10}],
AppendTo[req, BinaryRead[inStream]];
];
This is will work with properly formed requests but if the request is malformed the kernel crash is unavoidable as far as I can see. I realize implementing an HTTP server in Mathematica is a silly endeavour but I would like to know if there is a way of detecting the "end" of a socket stream for other potentially nontrivial uses of SocketLink
.
Comments
Post a Comment