springboot+websocket+sockjs进行消息发送

1.添加maven相关依赖


 
            org.springframework.boot
            spring-boot-starter-websocket
            2.1.6.RELEASE
        

2.添加websocket配置类


@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS();
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/user","/message");
    }
}

继承AbstractWebSocketMessageBrokerConfigurer类实现 registerStompEndpoints方法,其中registry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS()是指用来注册一个STOMP节点,并指定映射的url为"/socket",同时指定使用SockJS协议。registry.enableSimpleBroker用于配置消息代理,"/user"配置的是点对点代理,即在线聊天,"/message"配置的是消息发出后的通知的路径。

3.前端实现js部分代码


var id = $("#id").val();
    console.log("id is" + id);
    var sockJs = new SockJS("http://localhost:8080/socket");
    var stompClient = Stomp.over(sockJs);
    stompClient.connect({}, function (data) {
        stompClient.subscribe("/user/" + id + "/message/get", function (response) {
            console.log(response.body);
            $("#msg").append(response.body + "
") }) }) function sendmsg() { var sendid = $("#ids").val(); var message = $("#sendmsg").val(); stompClient.send("/message", {}, JSON.stringify({ msg: message, toUser: sendid, fromUser: id })); }

SockJs后的端口号对应了位置类中的"/socket",stompClient.subscribe表示接收消息的路径,stompClient.send("/message"表示发送消息的路径。

4.Controller部分


@Controller
public class ChatController {
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @GetMapping("/user/{id}")
    public String userChat(@PathVariable(value = "id") int id, Model model){
        model.addAttribute("id",id);
        return "chat";
    }

    @MessageMapping("/message")
    public void sendMessage(Message message){
        simpMessagingTemplate.convertAndSendToUser(message.getToUser(),"/message/get",message.getMsg());
        simpMessagingTemplate.convertAndSendToUser(message.getFromUser(),"/message/get",message.getMsg());
    }
}

自动注入SimpMessagingTemplate类用来发送消息到前端,"/user"路径通过传进的id不同来区分发送消息的人,服务器接收消息的接口是"/message",接收到以后在convertAndSendToUser方法调用发送给对应的id的用户.综上所述实现了一个简单的一对一单点发消息功能。

你可能感兴趣的:(springboot+websocket+sockjs进行消息发送)