Springboot 整合websocket

本文介绍了如何在Springboot项目中集成WebSocket,包括必要的Maven依赖引入,详细讲解了一个配置类的实现,并提供了后台和前端的示例代码,帮助开发者快速理解和应用WebSocket通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要引入maven

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

然后和其他不同的是需要写一个配置类 (唯一不同的地方)

@Configuration
public class SocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {

        return new ServerEndpointExporter();
    }

}

附带贴一个后台代码

@Component
@ServerEndpoint("/websocket/{username}")
public class WebSocket {

    public static int onlineCount = 0;
    public static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
//    public Session session;
    public Session session;
    public String username ;

    @OnOpen
    public void onOpen(Session session,@PathParam("username") String username) throws IOException {

        this.session = session;

        addOnlineCount();
        clients.put(username, this);
//        sendMessageAll(username+"进入了聊天室!\n");  //给全部的人发消息
        System.out.println("connect !");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(username);
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        System.out.println(message);


//            sendMessageAll(message);
//        JSONObject jsonTo = JSONObject.fromObject(message);
//
//        clients.get("zhangxi").session.getAsyncRemote().sendText("张喜属猪的"); //给指定的人发消息

    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public static void   sendMessageTo(String message, String To) throws IOException {
        System.out.println("clients:\n"+clients);
        WebSocket.clients.get("zhangxi").session.getAsyncRemote().sendText(message);
    }

    public void sendMessageAll(String message) throws IOException {
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

    public static synchronized Map<String, WebSocket> getClients() {
        return clients;
    }
}

都贴了后台了 那就顺便贴一个前端代码

function getconn() {

     var websocket = null;
    var username = document.getElementById("name").value;

    //判断当前浏览器是否支持WebSocket  
    if ('WebSocket' in window) {

        // websocket = new WebSocket("ws://localhost:8080/unnamed/websocket/"+username);
        //  websocket = new WebSocket("ws://localhost:8080/unnamed");
        websocket = new WebSocket("ws://localhost:9696/websocket/" + username);

        // alert("当前浏览器支持");
    } else {
        alert('当前浏览器 Not support websocket');
    }
    //连接发生错误的回调方法  
    websocket.onerror = function () {
        alert("发生错误");
        // setMessageInnerHTML("WebSocket连接发生错误");
    };
    //连接成功建立的回调方法  
    websocket.onopen = function () {
        alert("链接成功");
        // var msg = "{\"To\": \"tom\"}"
        // websocket.send(msg)
        // setMessageInnerHTML("WebSocket连接成功");

    }
    //接收到消息的回调方法  
    websocket.onmessage = function (event) {
        // alert("j接收到消息");
        // alert(event.data);
        document.getElementById("textarea").value +=event.data+"\n";
        // setMessageInnerHTML(event.data);
    }
    //连接关闭的回调方法  
    websocket.onclose = function () {
        alert("连接关闭");
        // setMessageInnerHTML("WebSocket连接关闭");
    }
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    //关闭WebSocket连接  
    function closeWebSocket() {
        websocket.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值