博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot + WebSocket 实现前后端的收发消息
阅读量:2094 次
发布时间:2019-04-29

本文共 4462 字,大约阅读时间需要 14 分钟。

灵魂拷问:什么是 WebSocket?它能解决什么问题?

360百科:

WebSocket 协议是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信--允许服务器主动发送信息给客户端。在 WebSocket 产生之前,双工通信是通过不停发送HTTP请求,从服务器拉取更新来实现,这导致了效率低下。

 

WebSocket 工作原理

在实现websocket连线过程中,需要通过浏览器发出websocket连线请求,然后服务器发出回应,这个过程通常称为"握手" 。在 WebSocket API,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。在此WebSocket 协议中,为我们实现即时服务带来了两大好处:

1. Header

互相沟通的Header是很小的-大概只有 2 Bytes

2. Server Push

服务器的推送,服务器不再被动的接收到浏览器的请求之后才返回数据,而是在有新数据时就主动推送给浏览器。

 

我们创建一个 SpringBoot 工程,实现用户A发送消息给用户B,B能及时收到。B也能给A发送消息。

代码结构:

 

pom.xml 

4.0.0
com.study
study-websocket
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
org.springframework.boot
spring-boot-starter-websocket
2.1.18.RELEASE

配置文件:application.yml

server:  port: 80

index.html

    SpringBoot 整合 WebSocket对方ID:
消息内容:
   
对方说:

配置类 WebSocketConfig:

package com.study.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.server.standard.ServerEndpointExporter;/** * @author biandan * @description * @signature 让天下没有难写的代码 * @create 2021-06-21 下午 8:35 */@Configurationpublic class WebSocketConfig {    @Bean    public ServerEndpointExporter serverEndpointExporter() {        return new ServerEndpointExporter();    }}

核心类处理类 MyWebSocket:

package com.study.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;import javax.websocket.*;import javax.websocket.server.ServerEndpoint;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;/** * @author biandan * @description * @signature 让天下没有难写的代码 * @create 2021-06-21 下午 10:19 */@ServerEndpoint(value = "/send")@Component@Slf4jpublic class MyWebSocket {    //在线人数    private static AtomicInteger onlineCount = new AtomicInteger(0);    //在线客户端    private static Map
clientsMap = new ConcurrentHashMap<>(); //连接建立成功调用的方法 @OnOpen public void onOpen(Session session) { //在线数 +1 onlineCount.incrementAndGet(); clientsMap.put(session.getId(), session); log.info("有新的客户端连接加入,客户ID={},当前总在线人数为:{}", session.getId(), onlineCount.get()); } //接收消息,并回传 @OnMessage public void onMessage(String message, Session session) { log.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message); try { String[] split = message.split(","); String userId = split[0]; String msg = split[1]; Session toSession = clientsMap.get(userId); if (toSession != null) { this.sendMessage(msg, toSession); } } catch (Exception e) { log.error(e.getMessage(), e); } } @OnError public void onError(Session session, Throwable error) { log.error(error.getMessage(), error); } /** * 服务端发送消息给客户端 */ private void sendMessage(String message, Session toSession) { try { log.info("服务端给客户端【" + toSession + "】发送消息:" + message); toSession.getBasicRemote().sendText(message); } catch (Exception e) { log.error("服务端给客户端发送消息失败:", e); } } //关闭连接 @OnClose public void onClose(Session session) { //在线数 -1 onlineCount.decrementAndGet(); clientsMap.remove(session.getId()); log.info("有客户端连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get()); }}

启动类:

package com.study;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * @author biandan * @description * @signature 让天下没有难写的代码 * @create 2021-06-21 下午 8:35 */@SpringBootApplicationpublic class WebSocketApp {    public static void main(String[] args) {        SpringApplication.run(WebSocketApp.class, args);    }}

 

启动服务,浏览器输入:   分开两个浏览器。

然后输入另外一个客户ID,可以在后台查看:

然后,两个客户端就可以互相通信了。

控制台:

 

 

转载地址:http://jkuhf.baihongyu.com/

你可能感兴趣的文章
如何避免自己写的代码成为别人眼中的一坨屎!
查看>>
Postman 安装及使用入门教程
查看>>
获取指定包下所有自定义注解并提取注解信息
查看>>
Windows 环境下 Git clone pull fetch 慢 解决之道
查看>>
Redis (error) NOAUTH Authentication required.解决方法
查看>>
plsql窗口中文显示的是横版的 问题解决办法
查看>>
使用notePad修改将文件格式保存后不起作用
查看>>
如何查询oracle会话及锁 如何查锁了哪张表?如何杀掉会话
查看>>
Git常用命令速查手册
查看>>
Redis运维利器 -- RedisManager
查看>>
分布式之REDIS复习精讲
查看>>
分布式之数据库和缓存双写一致性方案解析
查看>>
Redis集群
查看>>
Oracle 查看和扩展表空间
查看>>
记一次线上Java程序导致服务器CPU占用率过高的问题排除过程
查看>>
Java 内存溢出(java.lang.OutOfMemoryError)的常见情况和处理方式总结
查看>>
从cpu和内存来理解为什么数组比链表查询快
查看>>
CentOS7下使用YUM安装MySQL5.6
查看>>
JVM内存空间
查看>>
Docker 守护进程+远程连接+安全访问+启动冲突解决办法 (完整收藏版)
查看>>