I've always used rest web services to transfert file between client and server but now I have to make this through web socket. This is the scenary: user requires file download by page interface, so start a http request to the server. The server start an async task to make the file request to another server through rest template. Meantime user receives message to inform him that the pdf creation is started. So on the server, when the file trasfert ends, I have to send the pdf to the client over web socket so he can see in a new page the pdf. Until today I've used HttpServletResponse, can you help me with web socket? This is the controller for the file request:

@RequestMapping(path = "/pdf", method = RequestMethod.PUT)
@ResponseBody
public void getIndicatorPdf(@RequestBody String htmlCode) throws Exception {
    System.out.println("PDF REQUEST");
    indicatorServices.getIndicatorPdf(htmlCode);    
}

The service to make request to the other server:

public void getIndicatorPdf(String htmlCode) {
    //It should be retrieved from property file
    String url = "http://localhost:8090/users/testFile";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_PDF));
    HttpEntity<String> entity = new HttpEntity<>(htmlCode, headers);
    //Simulate elaboration time
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ResponseEntity<byte[]> response = restTemplate.exchange(url, 
    HttpMethod.PUT, entity, byte[].class);
    //Method to send file over socket
    User user = userRepository.findByUsername(principal.getName());
    this.template.convertAndSend("/topic/users/" + user.getId() +  "/indicators/pdf", response.getBody());}

Now I have to send the byte array over the socket to the client. If I send the response.getBody() the socket makes the disconnect, if I send a string message all work fine. How can send the file over the socket? The conversion to Message (ok, but how?) is the correct way even with large file?

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.