Skip to main content

windows - Implementing Local HTTP Server


How might I implement a local HTTP server using either Java, C#, C or purely Mathematica?


It should be able to respond with Mathematica input to GET and POST requests ideally on W7.


This is related although doesn't really work. If you would like you can read the license here



Answer



The following guide shows how to conduct communication between nanohttpd, an http server for Java, and Mathematica. The result is a server that, if you go to its address in a web browser, displays the result of SessionTime[], i.e. the time since the Mathematica kernel associated to the server started.


I'm going to write as if the reader was using OS X with Maven installed because that is the operating system I am using, but this solution works on all operating systems with the proper, obvious, modifications. Directories and so on. On OS X Maven can be installed with Brew using


brew -install maven


Getting up and running with nanohttpd:




  1. Download the latest version of nanohttpd from Github.




  2. Follow the steps listed under "quickstart" on nanohttpd.org





Add this to the top of the sample app among the other imports:


import com.wolfram.jlink.*;

Locate JLink.jar on your harddrive. On OS X it is located at


/Applications/Mathematica.app/SystemFiles/Links/JLink

Navigate to the app's directory and run the following command to include JLink.jar in the Maven project (with the appropriate modifications):


mvn install:install-file -Dfile=/Applications/Mathematica.app/Contents/SystemFiles/Links/JLink/JLink.jar -DgroupId=com.wolfram.jlink -DartifactId=JLink -Dversion=1.0 -Dpackaging=jar

And modify the app's pom.xml by adding the file as a dependency:



  
com.wolfram.jlink
JLink
1.0


Check that you can still compile the application and that it still works. Now if that's true, replace the code in App.java with this (see the sample program here):


import java.io.IOException;
import java.util.Map;
import com.wolfram.jlink.*;


import fi.iki.elonen.NanoHTTPD;

public class App extends NanoHTTPD {

KernelLink ml;

public App() throws IOException {
super(8888);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);


try {
String jLinkDir = "/Applications/Mathematica.app/SystemFiles/Links/JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir); // http://forums.wolfram.com/mathgroup/archive/2008/Aug/msg00664.html

ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname '\"/Applications/Mathematica.app/Contents/MacOS/MathKernel\" -mathlink'");

// Get rid of the initial InputNamePacket the kernel will send
// when it is launched.
ml.discardAnswer();

} catch (MathLinkException e) {
throw new IOException("Fatal error opening link: " + e.getMessage());
}

System.out.println("\nRunning! Point your browers to http://localhost:8888/ \n");
}

public static void main(String[] args) {
try {
new App();

} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
}
}

@Override
public Response serve(IHTTPSession session) {

String msg = "

";


try {
ml.evaluate("SessionTime[]");
ml.waitForAnswer();

double result = ml.getDouble();

msg = msg + Double.toString(result);
} catch (MathLinkException e) {
msg = msg + "MathLinkException occurred: " + e.getMessage();
}

msg = msg + "

";

return newFixedLengthResponse(msg);
}
}

Look up the line with String jLinkDir = and confirm that the directory is right. If you are using another operating system than OS X you also have to configure the line with MathLinkFactory in it. Information about that is available here.


Compile the code and run it by (as you did before to run the sample app), navigating to the project's directory and executing the following commands:


mvcompile
mvn exec:java -Dexec.mainClass="com.stackexchange.mathematica.App"


where you have edited mainClass appropriately. You now have an HTTP server on the address http://localhost:8888/ that calls on a Mathematica kernel and uses its response to answer requests.


Comments

Popular posts from this blog

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1.