如何使用Spring Web Sockets向特定用户发送消息?

时间:2017-04-06 12:38:24

标签: spring-mvc stomp spring-websocket sockjs

我无法使用Spring网络套接字向特定用户发送消息,这是我的代码。在我以前发送邮件的时候,我收到了org.springframework.messaging.simp.annotation.support.MissingSessionUserException: No "user" header in message

请告诉我如何避免这种情况。提前谢谢。

Controller.java

@MessageMapping("/sendMessage")

public void getMessage(String message,Principal principal){


    this.template.convertAndSendToUser(principal.getName(),"/topic/messages",message);


}

的index.jsp

function connect() {

            var socket = new SockJS('/SpringWebSocket/chat');
            stompClient = Stomp.over(socket);  
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClient.subscribe('/user/queue/messages', function(messageOutput) {

                alert("respose");
                });

            });
        }
function sendMessage() {
                        var from = document.getElementById('from').value;
                                    var text = document.getElementById('text').value;
                                    stompClient.send("/app/sendMessage",
                                            {}, JSON.stringify({
                                                'from' : from,
                                                'text' : text,

                                            }));

                                }

弹簧servlet.xml中:

<context:component-scan base-package="com.test"/>
<mvc:annotation-driven></mvc:annotation-driven>
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/">
    </property>
    <property name="suffix" value=".jsp">
    </property>
</bean>


 <websocket:message-broker application-destination-prefix="/app" >
    <websocket:stomp-endpoint path="/chat">
        <websocket:sockjs/>
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic, /queue"/>
</websocket:message-broker>

1 个答案:

答案 0 :(得分:0)

而不是this.template.convertAndSendToUser(principal.getName(),"/topic/messages",message); 使用this.template.convertAndSendToUser(principal.getName(),"/queue/messages",message);

之后