WebSocketController.java 2.19 KB
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.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;

@Controller
public class WebSocketController {
    @Autowired
    private WebSocketService webSocketService;

    @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/object")
    public void handleJsonMsgByWebsocket(@RequestBody StompPayload<Object> payload){
        webSocketService.send(WebsocketConstants.TOPIC_MESSAGE, payload);
    }

    /**
     * 服务器接收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){
        webSocketService.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){
        webSocketService.send(WebsocketConstants.TOPIC_MESSAGE, payload);
        return "ok";
    }


}