SpringBoot集成Socket

什么是Socket

在计算机通信领域,socket 被翻译为“套接字”,它是计算机之间进行通信的一种约定或一种方式。通过 socket 这种约定,一台计算机可以接收其他计算机的数据,也可以向其他计算机发送数据

Socket起源

socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,都可以用“打开open –> 读写write/read –> 关闭close”模式来操作。

Socket的主要作用

主要是用来解决网络通信的

本篇重点

Socket先了解这么多,更深的内容可以自行补充。本篇文章主要想实现 平台在线人数实时统计的功能

前后端
  • 后端:SpringBoot+Socket
  • 前端:Vue
具体步骤
引入依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
socket配置
@Configuration
public class WebSocketConfig {

   @Bean
   public ServerEndpointExporter serverEndpointExporter() {
      return new ServerEndpointExporter();
   }
}
WebSocketServer端
**
 * 由于是websocket 所以原本是@RestController的http形式
 * 直接替换成@ServerEndpoint即可,作用是一样的 就是指定一个地址
 * 表示定义一个websocket的Server端
 */
@Component
@ServerEndpoint("/websocket/{userId}")
public class MySocket {

    private Session session;

    private static CopyOnWriteArraySet<MySocket> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();
    /**
     * 有新的连接加入
     **/
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(shopId, session);
        // 新的连接加入 通知客户端
        sendMessageToAll(webSockets.size() + "");
        System.out.println("【websocket消息】有新的连接,总数为:" + webSockets.size());
    }
    /**
     * websocket消息连接断开
     **/
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        // 断开连接 通知客户端
        sendMessageToAll(webSockets.size() + "");
        System.out.println("【websocket消息】连接断开,总数为:" + webSockets.size());
    }
    /**
     * websocket消息收到客户端消息
     **/
    @OnMessage
    public void onMessage(String message) {
        System.out.println("websocket消息收到客户端消息:" + message);
    }
    /**
     * 通知所有的客户端
     *
     * @param message
     */
    public void sendMessageToAll(String message) {
        for (MySocket webSocket : webSockets) {
            System.out.println("【websocket】通知所有的客户端:" + message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Vue代码
export default {        
	created() { 
		// 页面创建 生命周期函数              
		this.initWebSocket()        
	},        
	destroyed: function () { 
		// 页面销毁生命周期函数              
		this.websocketclose();        
	},        
	methods: {            
		initWebSocket: function () {                
			// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https                
			this.websock = new WebSocket("ws://localhost:8080/websocket/userId");                
			this.websock.onopen = this.websocketonopen;                
			this.websock.onerror = this.websocketonerror;                
			this.websock.onmessage = this.websocketonmessage;                
			this.websock.onclose = this.websocketclose;              
		},              
		websocketonopen: function () {                
			console.log("WebSocket连接成功...");              
		},              
		websocketonerror: function (e) {                
			console.log("WebSocket连接发生错误...");              
		},              
		websocketonmessage: function (e) {                
        console.log(e.data);
        if (e.data !== undefined) {
          this.onlineUser = e.data
        }         
		},              
		websocketclose: function (e) {                
			console.log("connection closed (" + e.code + ")");              
		}
}
拦截器设置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
.antMatchers("/websocket/**"").permitAll()
                .anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

  • 测试-项目启动后台
  • 测试-启动前台-效果
    在这里插入图片描述
测试-查看后台日志打印及界面

在这里插入图片描述
在这里插入图片描述

测试-打开第二个浏览器后查看后台日志打印

在这里插入图片描述
在这里插入图片描述

测试-关闭一个浏览器后查看

在这里插入图片描述

小结

本篇主要以一个小case介绍了socket的用法,希望能对初接触
的小伙伴有些借鉴。要彻底搞懂Socket还要进一步深入

最近听到一句话,很有感触,送给大家 “基础不牢,地动山摇”!小伙伴们一起加油!

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Spring Boot可以很方便地集成Socket,实现WebSocket通信。以下是简单的步骤: 1. 添加依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket处理器 创建一个类,实现WebSocketHandler接口,处理WebSocket请求。例如: ``` @Component public class MyWebSocketHandler implements WebSocketHandler { @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { // 连接建立后的处理 } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { // 处理收到的消息 } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { // 处理传输错误 } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { // 连接关闭后的处理 } @Override public boolean supportsPartialMessages() { return false; } } ``` 3. 配置WebSocket 在配置类中添加WebSocket配置: ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private MyWebSocketHandler myWebSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler, "/my-websocket"); } } ``` 4. 测试WebSocket 在前端页面中使用JavaScript创建WebSocket连接,发送和接收消息。例如: ``` var socket = new WebSocket("ws://localhost:808/my-websocket"); socket.onopen = function(event) { console.log("WebSocket连接已建立"); }; socket.onmessage = function(event) { console.log("收到消息:" + event.data); }; socket.onclose = function(event) { console.log("WebSocket连接已关闭"); }; socket.send("Hello, WebSocket!"); ``` 以上是简单的Spring Boot集成Socket的步骤,具体实现还需要根据实际需求进行调整。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

qq_2760097491

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

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

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

打赏作者

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

抵扣说明:

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

余额充值