|
1
|
package com.huaheng.pc.stompwebsocket.controller;
|
|
2
|
|
|
3
4
5
|
import com.huaheng.pc.stompwebsocket.WebsocketConstants;
import com.huaheng.pc.stompwebsocket.domain.StompPayload;
import com.huaheng.pc.stompwebsocket.service.StompWebSocketServiceImpl;
|
|
6
|
import org.springframework.messaging.Message;
|
|
7
8
9
|
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
|
|
10
|
import org.springframework.util.LinkedMultiValueMap;
|
|
11
12
13
14
15
|
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;
|
|
16
17
|
import javax.annotation.Resource;
|
|
18
19
|
@Controller
public class WebSocketController {
|
|
20
21
|
@Resource
private StompWebSocketServiceImpl stompWebSocketService;
|
|
22
|
|
|
23
24
25
26
27
|
@GetMapping("/monitor/websocket")
public String manage(){
return "/monitor/websocket/manage";
}
|
|
28
|
|
|
29
30
31
32
33
34
35
|
/**
* 服务器接收websocket上行的普通文本消息,再通过websocket广播出去
*/
@MessageMapping("/websocket/message/string")
@SendTo(WebsocketConstants.TOPIC_MESSAGE)
public String handleStringMsgByWebsocket(String msg){
return msg;
|
|
36
37
|
}
|
|
38
39
40
41
42
|
/**
* 服务器接收websocket上行的json消息,再通过websocket发送出去
*/
@MessageMapping("/websocket/message/json/object")
public void handleJsonMsgByWebsocket(@RequestBody StompPayload<Object> payload){
|
|
43
|
stompWebSocketService.send(WebsocketConstants.TOPIC_MESSAGE, payload);
|
|
44
45
|
}
|
|
46
|
/**
|
|
47
48
49
50
51
52
53
54
55
|
* 服务器接收confirm消息
*/
@MessageMapping("/websocket/message/confirm")
public void handleConfirmMsgByWebsocket(Message headers){
String msg_id = ((LinkedMultiValueMap<String, String>) headers.getHeaders().get("nativeHeaders")).get("msg-id").get(0);
stompWebSocketService.confirmMsg(msg_id);
}
/**
|
|
56
57
58
59
|
* 服务器接收httpget上行的普通文本消息,再通过websocket广播出去
* http://127.0.0.1:8888/wms/websocket/message/string?msg=huaheng_robot
*/
@GetMapping("/websocket/message/string")
|
|
60
|
@ResponseBody
|
|
61
|
public String handleStringMsgByHttpGet(String msg){
|
|
62
|
stompWebSocketService.sendMessageBroadcast(WebsocketConstants.TOPIC_MESSAGE, msg);
|
|
63
64
65
|
return "ok";
}
|
|
66
67
68
69
70
71
|
/**
* 服务器接收httppost上行的json消息,再通过websocket广播出去
* StompPayload中封装目标用户和消息体
* http://127.0.0.1:8888/wms/websocket/message/json
*/
@PostMapping("/websocket/message/json")
|
|
72
|
@ResponseBody
|
|
73
|
public String handleJsonMsgByHttpPost(@RequestBody StompPayload<Object> payload){
|
|
74
|
stompWebSocketService.send(WebsocketConstants.TOPIC_MESSAGE, payload);
|
|
75
76
|
return "ok";
}
|
|
77
78
|
|
|
79
|
}
|