Web server script running continuosly

49 Views Asked by At

what I'm trying to do is a web server that simply answers clients requests. I am able to use PHP scripts, an executable written in C++ or services written in Java to create the response, but the problem is they always have to be loaded with every request from the client, which lowers the efficiency and requires me to save data in some file or db to exchange them between requests (can't use sessions, exchanging data between various clients).

So I'm looking for some script that would run continuosly on the server, "listen" to incomming requests, produce an answer and send it back. Useful, but not necessary features would be:
- based on C/C++, but doesn't have to be
- able to deal with http, since the clients is a website sending JSON
- can be easily used with some server solution

My idea was like having a one C++ program running continuously maintaining all the informations in the CPU and sharing it's memory with small programs, that would be started with each request comming, that would grab the data from the shared memory and do some processing to create the answer (no extensive computing, can be loaded multiple times). Does it sound a little possible?

Would be enough to name some technology work checking out, thank you, Martin C.

1

There are 1 best solutions below

1
On

I'm not sure why you think that you cannot do this with java servlets, but you're wrong. Or maybe I don't understand what you want to do.

Servlets have an init() method that you can use to initialize data when the application server starts. This data is then accessible to all requests, e.g.:

@WebServlet(urlPatterns="/somePath", loadOnStartup=1)
public class MyServlet extends HttpServlet {
    private Object sharedData;

    @Override
    public void init() throws ServletException {
        sharedData = <Your code to load data>
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(sharedData); // This is just an example of using sharedData
        ...
    }
}

Note that there is only one instance of the servlet, so data will be loaded only once and the same servlet instance will serve all requests (with multiple threads).

If requests can also modify the shared data, you have to be carefull to keep the code thread-safe. But if you're only reading it, it's pretty simple.