一看就懂!Springboot +WebSocket 实现点对点/广播聊天

WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

现在,很多网站为了实现推送技术,所用的技术都是 Ajax 轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。

HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。

轮询: 不断地向服务器发送请求,服务器也频繁的被动回应请求;

WebSocket:由服务器向客户端主动发起回应;

详细介绍自行百度啦,这里介绍Springboot如何整合WebSocket,

代码已上传的git:https://github.com/FENGZHIJIE1998/websocket-demo

1. pom.xml

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2. WebSocketConfig

/**
 * @author Dazhi
 * @date 2019/4/25 20:40
 */
@Component
public class WebSocketConfig {

    /**
     * 注入ServerEndpointExporter
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

}

3. MessageVO

/**
 * @author Dazhi
 * @date 2019/4/25 20:45
 */
@Data
public class MessageVo {

    /**
     * 消息生产者ID
     */
    private String productorId;
    /**
     * 消息消费者者ID
     */
    private String comsumerId;
    /**
     * 消息
     */
    private String message;
    /**
     * 生产者昵称
     */
    private String nickname;
}

4. WebSocketServer(重点)

/**
 * @author Dazhi
 * @date 2019/4/25 20:50
 */

@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocket {
    /**
     * String : 用户ID
     * Session: 回话
     */
    public static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();

    /**
     * onOpen是当用户发起连接时,会生成一个用户的Session 注意此Session是 javax.websocket.Session;
     * 然后我们用userId作为Key Session作为Vaule存入Map中暂存起来
     *
     * @param userId
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        log.info("====>WebSocketService onOpen: " +
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
这里给出一个简单的SpringBoot + Vue + websocket实现的一对一聊天的代码示例。 后端代码(基于SpringBoot): ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer{ @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new ChatWebSocketHandler(), "/chat"); } } @Component public class ChatWebSocketHandler extends TextWebSocketHandler { private static final List<WebSocketSession> sessions = new ArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); session.sendMessage(new TextMessage("欢迎来到聊天室!")); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { for (WebSocketSession s : sessions) { if (s != session) { s.sendMessage(new TextMessage(message.getPayload())); } } } } ``` 前端代码(基于Vue): ```html <template> <div> <div v-for="(message, index) in messages" :key="index"> {{ message }} </div> <input type="text" v-model="input" @keydown.enter="sendMessage" /> </div> </template> <script> import SockJS from 'sockjs-client'; import Stomp from 'stompjs'; export default { data() { return { input: '', messages: [], }; }, methods: { connect() { const socket = new SockJS('/chat'); this.stompClient = Stomp.over(socket); this.stompClient.connect({}, (frame) => { this.stompClient.subscribe('/topic/chat', (response) => { this.messages.push(response.body); }); }); }, disconnect() { if (this.stompClient != null) { this.stompClient.disconnect(); } }, sendMessage() { if (this.input !== '') { this.stompClient.send('/app/chat', {}, this.input); this.input = ''; } }, }, created() { this.connect(); }, beforeDestroy() { this.disconnect(); }, }; </script> ``` 在这个例子中,我们使用了SockJS和Stomp.js来实现websocket的客户端连接。在前端中,我们使用connect方法来连接到websocket,disconnect方法来断开连接,sendMessage方法来发送信息。在后端中,我们使用TextWebSocketHandler来处理websocket连接,afterConnectionEstablished方法用于建立连接,handleTextMessage方法用于处理收到的信息。 需要注意的是,这里的聊天室只支持一对多的聊天,如果需要实现一对一的聊天,需要在后端代码中对应修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大誌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值