WebSocketController.java 2.97 KB
package com.huaheng.pc.stompwebsocket.controller;

import com.huaheng.pc.stompwebsocket.WebsocketConstants;
import com.huaheng.pc.stompwebsocket.domain.Message;
import com.huaheng.pc.stompwebsocket.domain.StompPayload;
import com.huaheng.pc.stompwebsocket.service.StompWebSocketServiceImpl;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
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 javax.annotation.Resource;

@Lazy
@Controller
public class WebSocketController {
    @Resource
    private StompWebSocketServiceImpl stompWebSocketService;

    @GetMapping("/monitor/websocket")
    public String manage(){
        return "monitor/websocket/manage";
    }


    /**
     * 服务器接收websocket上行的普通文本消息,再通过websocket广播出去
     */
    @MessageMapping("/websocket/message/string")
    @SendTo(WebsocketConstants.TOPIC_MESSAGE)
    public String handleStringMsgByWebsocket(String msg){
        return msg;
    }

    /**
     * 服务器接收websocket上行的json消息,再通过websocket发送出去
     */
    @MessageMapping("/websocket/message/json")
    public void handleJsonMsgByWebsocket(@RequestBody StompPayload<Message> payload){
        stompWebSocketService.send(WebsocketConstants.TOPIC_MESSAGE, payload);
    }

    /**
     * 服务器接收confirm消息
     */
    @MessageMapping("/websocket/message/confirm")
    public void handleConfirmMsgByWebsocket(org.springframework.messaging.Message headers){
        try{
            String msg_id = ((LinkedMultiValueMap<String, String>) headers.getHeaders().get("nativeHeaders")).get("msg-id").get(0);
            stompWebSocketService.confirmMsg(msg_id);
        }catch (Exception e){

        }

    }

    /**
     * 服务器接收httpget上行的普通文本消息,再通过websocket广播出去
     * http://127.0.0.1:8888/wms/websocket/message/string?msg=huaheng_robot
     */
    @GetMapping("/websocket/message/string")
    @ResponseBody
    public String handleStringMsgByHttpGet(String msg){
        stompWebSocketService.sendMessageBroadcast(WebsocketConstants.TOPIC_MESSAGE, msg);
        return "ok";
    }

    /**
     * 服务器接收httppost上行的json消息,再通过websocket广播出去
     * StompPayload中封装目标用户和消息体
     * http://127.0.0.1:8888/wms/websocket/message/json
     */
    @PostMapping("/websocket/message/json")
    @ResponseBody
    public String handleJsonMsgByHttpPost(@RequestBody StompPayload<Object> payload){
        stompWebSocketService.send(WebsocketConstants.TOPIC_MESSAGE, payload);
        return "ok";
    }


}