欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot简单集成WebSocket(纯后端)

程序员文章站 2022-03-19 16:11:01
SpringBoot简单集成WebSocket引入依赖 com.alibaba fastjson 1.2.7 org.sprin...

SpringBoot简单集成WebSocket(纯后端)

  1. 引入依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.7</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  1. 编写一个WebSocketConfig
package com.ksxx.test.service;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
  1. 编写一个ServerEncoder继承Encoder,这个编译器是为了可以发送对象信息
package com.ksxx.test;

import com.alibaba.fastjson.JSON;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

public class ServerEncoder implements Encoder.Text<Object> {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void init(EndpointConfig arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public String encode(Object obj) {
        return JSON.toJSONString(obj);
    }
}
  1. 编写一个WebSocketBacklogServer (其中type为类型,可多种连接类型)
package com.ksxx.test;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value="/websocket/{type}/{userId}", encoders = { ServerEncoder.class })
@Component
public class WebSocketBacklogServer {

    //存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap<String, WebSocketBacklogServer> webSocketSet = new ConcurrentHashMap<String, WebSocketBacklogServer>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    //接收userId
    private Integer userId;
    //类型    待办:backlog、消息数量:message、即时通讯:chat
    private String type;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") Integer userId,@PathParam("type") String type) {
        this.session = session;
        webSocketSet.put(type+","+userId,this);     //加入set中
        this.userId=userId;
        this.type=type;
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        System.out.println(userId+type);
        webSocketSet.remove(type+","+userId);  //从set中删除
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到来自窗口"+userId+"的关于"+type+"信息:"+messag);
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    
    /**
     * 推送
     */
    public void sendMessage(Object message) throws EncodeException,IOException {
        this.session.getBasicRemote().sendObject(message);
    }

    /**
     * 发送消息到所有客户端
     * @param message
     * @throws EncodeException
     * @throws IOException
     */
    public void sendMessageInAll(Object message) throws EncodeException,IOException {
        for(WebSocketBacklogServer value : webSocketSet.values()) {
            value.session.getBasicRemote().sendObject(message);
        }
    }

    /**
     * 指定给某个连接发送信息
     * */
    public static void sendInfo(Object message,Integer userId,String type) throws EncodeException,IOException {
        webSocketSet.get(type+","+userId).sendMessage(message);
    }

}
  1. 模拟客户端测试连接
    测试地址: http://www.jsons.cn/websocket/
    SpringBoot简单集成WebSocket(纯后端)
  2. 模拟客户端测试发送信息
    SpringBoot简单集成WebSocket(纯后端)
    SpringBoot简单集成WebSocket(纯后端)
  3. 服务端主动推送信息(对象类),创建一个Controller写一个测试方法测试调用一下即可
package com.ksxx.test.controller;

import com.ksxx.test.service.WebSocketBacklogServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("test")
public class TestController {

    @RequestMapping("aa")
    public void aa(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("age",13);
        try {
            WebSocketBacklogServer.sendInfo(jsonObject,1,"chat");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

本文地址:https://blog.csdn.net/October_zhang/article/details/111886986