WebSocketController.java 1.72 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.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";
    }
}