With Spring Boot, you could give spring-boot-starter-websocket
a try. A working tutorial projecte can be downloaded here:
https://spring.io/guides/gs/messaging-stomp-websocket/
A simpler approach to websockets (but also less flexible) is using StreamingResponseBody
as you already mentioned. The reason why the <br />
is not working as stated in your last comment is, that the default content type returned will be text/plain
. Update your controller like shown below to set the content type to HTML, so the browser will render it accordingly.
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
@Controller
public class StreamingController {
@RequestMapping(value = "/")
public ResponseEntity<StreamingResponseBody> handleRequest2() {
StreamingResponseBody stream = out -> {
for (int i = 0; i < 1000; i++) {
out.write((Integer.toString(i) + " - <br />").getBytes());
out.flush();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(stream);
}
}
\n").getBytes()); out.flush(); } This doesnt seem to work!!! – Ravi Salunkhe Nov 20 '20 at 16:28