首页 > 技术文章 > websocket笔记

yszzu 2019-11-01 18:44 原文

参考:
https://spring.io/guides/gs/messaging-stomp-websocket/
https://www.jianshu.com/p/4ef5004a1c81
https://juejin.im/post/5ce942c3f265da1bbd4b501f#heading-16

服务器端 要允许跨域

@Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*").withSockJS();
    }

服务器端的监听接口
和restcontroller一样, 不同点是返回结果是通过simpMessagingTemplate发送给socket客户端

@RequestMapping("/serverSendMsg")
    @ApiOperation("serverSendMsg")
    public String greetingx(String id) throws Exception {
        simpMessagingTemplate.convertAndSend("/topic/greetings/"+id, new Greeting("Hellfffffffffffo, " + id + "!"));
        return "success";
    }

长连接,要求nginx使用ip hash的方式固定转发给后台的一个机器 , 否则服务器回传就找不到socket了

连接建立只是完成握手, 之后要干什么事情 是另外再写方法 做client server交互

client发送方法, server收消息的方法
clent监听的方法, server发消息的方法

客户端要做连接重试, 数据幂等

推荐阅读