I want to create a Servlet, To which I can send data (GET/POST doesn't matter) after some time interval. It will be something like persistent connection from Client to server. Using this single connection I will be sending some data (String) to the Servlet time to time, where the data will be processed. so that I don't have to make new connection each time I want to send the data.
What I tried currently. Here is my pure Java Client:
try {
URL url = new URL("http://localhost:8080/MyProject/MyServletName");
HttpURLConnection connnection = (HttpURLConnection) url.openConnection();
connnection.setRequestMethod("GET");
connnection.setRequestProperty("Connection", "keep-alive");
connnection.setDoOutput(true);
OutputStream writer = connnection.getOutputStream();
String message = "message-";
int counter = 0;
while (counter < 30) {
Thread.sleep(1000);
message = "message-" + counter;
writer.write(message.getBytes());
writer.flush();
counter++;
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
So Ideally this client will be writing data to the output stream and flush it after 1 second. And the same I should get In my Servlet. Here is my servlet code (doGet method):
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
Now the servlet should print the line recieved from the client after each second. but the problem here is the servlet not even getting called. If I add the below line in my client class.
int HttpResult = connnection.getResponseCode();
Then the servlet is called, but it gets executed completely and do not wait for the data sent from the client. How Will make it work? It Should be there waiting for new data to come from the client. Any help would be appriciated. Thank You
What you are looking for is WebSocket.
This is a protocol that allows an initial HTTP connection to be "upgraded" to a persistent connection where either the client or the server can send messages at any time.
It's radically different from a standard HTTP servlet-style web application, so you'll have to change a lot of your application to cope with it. But your use-case is exactly why Websocket was created.
Apache Tomcat ships with some Websocket examples (both client and server) if you'd like to see how some of it is done.