loading...

springboot使用webSoket

1、pom依赖

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

2、config文件夹新增WebSocketServerEndpointConfig配置文件

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebSocketServerEndpointConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3、webSocket无法通过@Autowired注入bean(无法操作service层)

@ServerEndPoint中是无法使用@Autowired注入Bean的。大概原理如下:
在我们springboot项目启动的时候,WebSocket已经被注入了这个DeviceService的Bean,但是WebSocket的特点是:建立一个连接,会生成一个新的WebSocket对象,分析源码,也可以理解:每个请求后,建立一个连接生成一个新的WebSocket,故这样是不能获得自动注入的对象了。

1.在WebSocketController中加入以下代码:
//此处是解决无法注入的关键
private static ApplicationContext applicationContext;
//你要注入的service或者dao
private IChatService iChatService;
public static void setApplicationContext(ApplicationContext applicationContext) {
    WebSocketController.applicationContext = applicationContext;
}

2.使用时:
iChatService = applicationContext.getBean(IChatService.class);
iChatService.save(chat);

3.同时在启动类中也要加入一些代码
public static void main(String[] args) {
    SpringApplication springApplication = new SpringApplication(Demo1Application.class);
    ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
    //解决WebSocket不能注入的问题
    WebSocketController.setApplicationContext(configurableApplicationContext);
    //SpringApplication.run(Demo1Application.class, args);
}

4、加入了webSocket打包报错

// 在ApplicationTests中添加
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

5、WebSocketController完整代码

import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSONObject;
import com.example.demo1.entity.Chat;
import com.example.demo1.service.IChatService;
import com.example.demo1.util.DateUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/*@ServerEndpoint注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/websocket/{userID}")
@Component
public class WebSocketController {

    //每个客户端都会有相应的session,服务端可以发送相关消息
    private Session session;

    //接收userID
    private Integer userID;

    //J.U.C包下线程安全的类,主要用来存放每个客户端对应的webSocket连接
    private static CopyOnWriteArraySet<WebSocketController> copyOnWriteArraySet = new CopyOnWriteArraySet<WebSocketController>();

    //此处是解决无法注入的关键
    private static ApplicationContext applicationContext;

    //你要注入的service或者dao
    private IChatService iChatService;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketController.applicationContext = applicationContext;
    }

    public Integer getUserID() {
        return userID;
    }

    // 打开连接。进入页面后会自动发请求到此进行连接
    @OnOpen
    public void onOpen(Session session, @PathParam("userID") Integer userID) {
        this.session = session;
        this.userID = userID;
        System.out.println("sessionID:" + this.session.getId());
        System.out.println("userID:" + userID);
        copyOnWriteArraySet.add(this);
        System.out.println("websocket有新的连接, 总数:"+ copyOnWriteArraySet.size());
    }

    // 用户关闭页面,即关闭连接
    @OnClose
    public void onClose() {
        copyOnWriteArraySet.remove(this);
        System.out.println("websocket连接断开, 总数:"+ copyOnWriteArraySet.size());
    }

    // 测试客户端发送消息,测试是否联通
    @OnMessage
    public void onMessage(String message) throws Exception {
        System.out.println("websocket收到客户端发来的消息:"+message);
        JSONObject server = (JSONObject) JSONObject.parse(message);
        Chat chat = new Chat();
        chat.setSendTime(DateUtil.currentDateStr(""));
        chat.setContent(server.getString("content"));
        chat.setFromId(server.getInteger("fromId"));
        chat.setToId(server.getInteger("toId"));
        try {
            //此处是解决无法注入的关键
            iChatService = applicationContext.getBean(IChatService.class);
            iChatService.save(chat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        sendMessage(server.getInteger("toId"),message);
    }

    // 出现错误
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误:" + error.getMessage() + "; sessionId:" + session.getId());
        error.printStackTrace();
    }

    public void sendMessage(Object object){
        //遍历客户端
        for (WebSocketController webSocket : copyOnWriteArraySet) {
            System.out.println("websocket广播消息:" + object.toString());
            try {
                //服务器主动推送
                webSocket.session.getBasicRemote().sendObject(object) ;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 用于发送给客户端消息(群发)
    public void sendMessage(String message) {
        //遍历客户端
        for (WebSocketController webSocket : copyOnWriteArraySet) {
            System.out.println("websocket广播消息:" + message);
            try {
                //服务器主动推送
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 用于发送给指定客户端消息
    public void sendMessage(Integer userID, String message) throws Exception {
        Session session = null;
        WebSocketController tempWebSocket = null;
        for (WebSocketController webSocket : copyOnWriteArraySet) {
            if (webSocket.getUserID() == userID) {
                tempWebSocket = webSocket;
                session = webSocket.session;
                break;
            }
        }
        if (session != null) {
            //服务器主动推送
            tempWebSocket.session.getBasicRemote().sendText(message);
        } else {
            System.out.println("没有找到你指定ID的会话:{}"+ "; userId:" + userID);
        }
    }
}
posted @ 2020-11-06 17:30  浮生若梦~  阅读(166)  评论(0编辑  收藏  举报