SimpMessagingTemplate不向websocket发送消息

时间:2016-08-12 13:56:05

标签: spring-websocket

我有以下控制器

//global variable declaration like a string or data source e.g
String myValue;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.bar_pics_grid, container, false);
    //Get your global variable here
    String getValue = myValue;
    GridView gridview = (GridView) v.findViewById(R.id.gridview);

    return v;
}


public void loadData(String bar) {

    //initialize your global variable here
    myValue = bar;
}

我的配置是

@Controller
public class GreetingController 
{
        @MessageMapping("/hello")
        @SendTo("/topic/greetings")
        public Person greeting(String message) throws Exception {
                Person person=new Person();
                person.setAge(10);
                return person;
        }
        @Autowired
        private SimpMessagingTemplate template;

        @RequestMapping(path="/meeting",method=RequestMethod.POST)
        public  @ResponseBody void greet() {
            this.template.convertAndSend("/topic/greetings", "message");
         }
    }

因此,根据spring doc template.convertAndSend(" / topic / greetings"," message")应该调用代理,并且将调用映射的Web套接字。

使用SockJS的前端代码

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig1 extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/hello").withSockJS();
    }
}

控制台中没有错误。我可以通过SockJs连接它并发送消息到" / topic / greetings"但我想调用一个webService,它反过来调用web Socket。因此,经过大量搜索后我没有错误,并且无法在春季找到不同的方法。

2 个答案:

答案 0 :(得分:0)

@RequestMapping(path="/meeting",method=RequestMethod.POST)不能使用,因为它是@Controller而不是@RestController

答案 1 :(得分:0)

我运行了您的代码,而不是发送简单的字符串,您应该发送对象 所以代替

this.template.convertAndSend("/topic/greetings", "message");

应该是

this.template.convertAndSend("/topic/greetings", messageObject);

并且您的对象应该具有某种访问内容的方法 喜欢

MessageObject.getConent();

否则,您始终可以使用toString()

您的js应该是

stompClient.subscribe('/topic/greetings', function(greeting){
    console.log(JSON.parse(greeting.body).content);
});

在接收到的对象末尾注意内容