我只是按照spring的指示将响应发回给特定用户,而不是广播消息,但是最后没有响应消息可以发回。

这是我的js代码:

var stompClient = null;
function setConnected(connected) {
    document.getElementById('connect').disabled = connected;
    document.getElementById('disconnect').disabled = !connected;
    document.getElementById('conversationDiv').style.visibility =
            connected ? 'visible': 'hidden';
    document.getElementById('response').innerHTML = '';
}
function connect() {
    var socket = new SockJS('reqsample');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('user/queue/resp', function(resp) {
            var body = JSON.parse(resp.body);
            showResp('cmid:' + body.cmid + ',reqName:' + body.reqName
                    + ',custNo:' + body.custNo + ',qty:' + body.quantity);
        });
        stompClient.subscribe('user/queue/errors', function(resp) {
            var body = JSON.parse(resp.body);
            showResp(body);
        });
    });
}
function disconnect() {
    stompClient.disconnect();
    setConnected(false);
    console.log("Disconnected");
}
function sendName() {
    var name = document.getElementById('name').value;
    stompClient.send("/app/req", {}, JSON.stringify({
        'name' : name
    }));
}


这是控制器:

@Controller
public class MessageController {
    @MessageMapping("/req")
    @SendToUser("/queue/resp")
    public RespMessage greeting(ReqMessage message, Principal pc)
        throws Exception {
    System.out.println("---- received message: " + message == null ? "NULL"
            : message.getName());
    System.out.println("---- received user info: " + pc.getName());
    RespMessage rm = new RespMessage();
    rm.setCmid("CM_01");
    rm.setCustNo("Cust_02");
    rm.setQuantity("1000");
    rm.setReqName(message.getName());
    return rm;

    }

    @MessageExceptionHandler
    @SendToUser("/queues/errors")
    public String handleException(Exception ex) {
        System.out.println(ex);
        return ex.getMessage();
    }

    }


这是弹簧配置:

<context:component-scan base-package="wx.poc7" />
<mvc:annotation-driven />
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/js/**" location="/js/" />
<websocket:message-broker
    application-destination-prefix="/app" user-destination-prefix="/user">
    <websocket:stomp-endpoint path="reqsample">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/queue, /topic" />
 </websocket:message-broker>


请帮助。提前。

我已经尝试使用@SendToUser,@ SendToUser(“ / queue / resp”)和SimpMessagingTemplate,完全无法响应浏览器的消息。

最佳答案

用户目标前缀为/user,但似乎您缺少订阅目标中的/。将user/queue/resp更改为/user/queue/resp以在客户端接收消息。

10-07 18:03