美文网首页
websocket简单应用—聊天

websocket简单应用—聊天

作者: 莫以有 | 来源:发表于2019-04-18 09:19 被阅读0次
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输
  • 添加依赖
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
  • 定义静态变量,记录在线人数
 private static int onlineCount = 0;
  • 存放对象
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet
            = new CopyOnWriteArraySet<WebSocketServer>();
  • 通过session进行请求
 private Session session;
  • 连接成功调用的方法
  @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //将客户端加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新窗口开始监听,当前在线人数为"
                + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            System.out.println("WebSocket IO异常");
        }
    }
  • 连接关闭调用的方法
 @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有连接关闭!当前在线人数为" + getOnlineCount());
    }
  • 收到消息
 @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到客户端的信息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 错误提示
  @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }
  • 允许进行swagger测试
@EnableSwagger2Doc
  • 测试


    swagger.png
  • 结果


    result.png
  • 与前台进行交互,就可以完成聊天功能

相关文章

网友评论

      本文标题:websocket简单应用—聊天

      本文链接:https://www.haomeiwen.com/subject/nsoawqtx.html