WebSocketController.java
1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.huaheng.framework.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
@Controller
public class WebSocketController {
@Autowired
private WebSocketService webSocketService;
@MessageMapping("/helloByWebSocket")
@SendTo("/topic/hello")
public String helloByWebSocket(String name) throws Exception{
return "Hello, " + HtmlUtils.htmlEscape(name) + "!";
}
@MessageMapping("/helloByWebSocket2")
@SendToUser("/queue/hello")
public String helloByWebSocket2(String name) throws Exception{
return "Hello, " + HtmlUtils.htmlEscape(name) + "!";
}
@GetMapping("/websocket/helloByHttpGet")
@ResponseBody
public String helloByHttpGet(String name) throws Exception{
webSocketService.broadcast("/queue/hello", "Hello, " + HtmlUtils.htmlEscape(name) + "!");
return "ok";
}
@PostMapping("/websocket/helloByHttpPost")
@ResponseBody
public String helloByHttpPost(@RequestBody Payload<DemoData> payload){
String user = "zf";
// webSocketService.broadcast("/queue/hello-user" + user, payload);
webSocketService.broadcast("/queue/hello", payload, user);
return "ok";
}
}