I'm new to web socket programming. I have more than 10 methods annotated with @GetMapping
, where the returned data is read from a MySQL database.
Can anyone help me to know how to write WebSockets.
My WebRestController.java looks like the below:
@CrossOrigin(origins = "http://localhost:4200", allowedHeaders="*")
@RestController
@RequestMapping("/api")
public class WebRestController {
@GetMapping("/summary")
public String Summary() { /* ... */}
@GetMapping("/erday")
public String Erday(String erday) { /* ... */}
@GetMapping("/count")
public String Count(@RequestParam Map<String,String> queryParam,
String date, String target) { /* ... */}
@GetMapping("/details")
public String Details(@RequestParam Map<String,String> queryParam,
String date, String target) { /* ... */}
@GetMapping("/devmawah")
public String DevMawah(@RequestParam Map<String,String> queryParam,
String date, String target) { /* ... */}
// ....
}
I tried before many times in internet to find the solution, but couldn't find it. All I found are examples for Chat applications, which have 2 endpoints to send and receive.
WebSockets are used for bi-directional communication, not really for REST style services (where HTTP is superior in my opinion). The core difference being that HTTP is fundamentally a request-reply protocol, which fits very well to REST whereas WebSocket is centred around messages. Of course, you can argue that request-reply is a specialisation of message-based communication.
There are several articles on this topic (google REST over WebSocket
) and even some StackOverflow questions which detail the pros and cons, for example Is ReST over websockets possible?.
The only way that I know of which allows you to do something resembling REST over WebSocket without having to re-write the RestController is swagger-socket, but I would not recommend using it as the project seems to be inactive now and it seems to not have been used extensively.
Alternatively, you can replace your @RequestMapping
or @GetMapping
annotations with @MessageMapping
annotations and model your API through messages (e.g. the client sends a "GET" message to a given destination, and you send back a message containing the resources).