SpringBoot 整合 Websocket 通信demo (附浏览器聊天窗口)

【男性深夜解压神器】


https://item.taobao.com/item.htm?spm=a21dvs.23580594.0.0.1d293d0dZgIXMJ&ft=t&id=742087626933

1. 依赖

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

2. 自动注册配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

 
3. WebSocket服务类

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.CopyOnWriteArraySet;


/**
 * postman访问: ws://localhost:8080/ws/{userId}
 * 浏览器访问:  http://localhost:8080/ws
 */
@Component
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {

    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private Session session;
    private String userId = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        this.userId = userId;
        sendMessage(userId + "用户" + ", 连接成功 !");

        System.out.println("【websocket】 " + userId + "用户" + "已连接!当前在线人数为" + getOnlineCount());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1

        System.out.println("【websocket】 " + userId +  "用户" +  "已关闭!当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session) {

        if(message.startsWith("target-")){
            int index = message.indexOf(":");
            String userId = message.substring(7,index);
            sendInfo(message.substring(index + 1), userId);
            return;
        }

        this.session = session;
        sendMessage("【websocket】 服务端收到来自窗口" + userId + "发送的消息:" + message);

    }

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

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 群发消息
    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) {
        System.out.println("【websocket】 推送消息给" + userId +  "用户" + ",推送内容:" + message);

        for (WebSocketServer item : webSocketSet) {
            //这里可以设定只推送给这个userId的,为null则全部推送
            if (userId == null) {
//                    item.sendMessage(message);
            } else if (item.userId.equals(userId)) {
                item.sendMessage(message);
            }
        }
    }


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

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

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

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}

4. 模拟通信

【websocket】 2015用户已连接!当前在线人数为1
【websocket】 7349用户已连接!当前在线人数为2
【websocket】 推送消息给7349用户,推送内容:你好, 我是2015用户, 很高兴认识你 !
【websocket】 推送消息给2015用户,推送内容:你好, 我是7349用户, 我也很高兴认识你 !

​
访问:http://localhost:8080/ws

可以打开多个

开始连接,一个客户端给另一个客户端发消息。

可以服务端推送消息给所有连接的客户端

POST:http://localhost:8080/push

任意内容

​

5. 需要完整代码的可私信我
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yixian123.com

谢谢打赏,祝老板心想事成

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

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

打赏作者

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

抵扣说明:

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

余额充值