Spring Boot实现Web Socket

原文链接:https://www.dubby.cn/detail.html?id=9102

实现代码

依赖

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

启动类

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

配置

@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Bean
    public ServerEndpointExporter serverEndpointExporter (){
        return new ServerEndpointExporter();
    }
}

WebSocket

@ServerEndpoint("/websocket")
@Component
public class MyWebSocket {
    private static AtomicLong onlineCount = new AtomicLong();
    private static ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session) {
        webSocketMap.put(session.getId(), session);
        System.out.println("有新链接加入!当前在线人数为:\t" + onlineCount.incrementAndGet());
    }
    @OnClose
    public void onClose(Session session) {
        webSocketMap.remove(session.getId());
        System.out.println("有一链接关闭!当前在线人数为:\t" + onlineCount.decrementAndGet());
    }
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("收到消息:\t" + message);
        if (message.contains("#")) {
            String[] msgMap = message.split("#");
            String targetId = msgMap[0];
            String msg = String.format("[%s]:\t%s", session.getId(), msgMap[1]);
            session.getBasicRemote().sendText(message + "[self]");
            // 单发消息
            for (Session item : webSocketMap.values()) {
                if (item.getId().equals(targetId)) {
                    sendMessage(item, msg);
                }
            }
        } else {
            String msg = String.format("[%s]:\t%s", session.getId(), message);
            session.getBasicRemote().sendText(msg + "[自己]");
            // 群发消息
            for (Session item : webSocketMap.values()) {
                if (!item.getId().equals(session.getId())) {
                    sendMessage(item, msg);
                }
            }
        }
    }
    private void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }
}

Github地址

https://github.com/dubby1994/web-socket

结果截图

第0个客户端

image

第1个客户端

image

第2个客户端

image

服务端

image
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 其实知道自己能量低,有这方面的意识,说明自己生活的不麻木。我观察自己好长一段时间了,从好几个方面就觉得自己能量低。...
    行靜阅读 10,252评论 0 0
  • 公众号里的图文消息如果插入腾讯视频,是必须在正文中加入文字的。而有些公众号发布的图文消息,正文只有视频,上面有一行...
    莉莉妮特阅读 12,931评论 4 5
  • 嘿~花粉儿们 你们期待已久的花花财经第八期节目更新啦! 大家千万不要错过哦~ 上一期呢,雅琴姐姐和嘉宾们给大家分享...
    蝉鸣三境阅读 164评论 0 0
  • 今天普度。 早上起来就开始收拾家里,因为晚上会有客人来,得保证家里干净敞亮。 吃早饭时,得知妈妈邀请了慧婷,慧婷答...
    里弗斯丶洁阅读 142评论 0 0
  • 一日 吃饭 饱了 放下筷子 一桌的人 纷纷夹起菜肴 放到面前的碗中 多吃点 一看你肯定没吃饱 千万不要饿着 菜还有...
    朱古里阅读 245评论 0 0