欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Springboot基于websocket实现简单在线聊天功能

时间:2020-11-20 17:47:23|栏目:JAVA代码|点击:

添加maven依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.5.RELEASE</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>springboot-websocket</artifactId>
  <name>springboot-websocket</name>

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

</project>

添加websocket配置

@Configuration
@EnableWebSocket
public class MyWebSocketConfig implements WebSocketConfigurer {
  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(myHandler(), "/myHandler").setAllowedOrigins("*");
  }

  @Bean
  public WebSocketHandler myHandler() {
    return new MyTextWebSocketHandler();
  }
}

实现具体的handler

public class MyTextWebSocketHandler extends TextWebSocketHandler {
  private Set<WebSocketSession> sessions = new HashSet<>();

  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    if (session.isOpen()) {
      sessions.add(session);
    }
    sendToAll(message);
  }
  private void sendToAll(TextMessage message) throws IOException {
    for (WebSocketSession session : sessions) {
      session.sendMessage(message);
    }
  }
  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    sessions.remove(session);
  }
}

即可通过ws://localhost:8080/myHandler访问websocket

添加测试页面:

<html>
<script type="text/javascript">
  if ("WebSocket" in window) {
    var ws = new WebSocket("ws://localhost:8080/myHandler");
    ws.onopen = function () {

    };

    ws.onmessage = function (evt) {
      document.getElementById('messageDiv').innerHTML += evt.data + "</br>";
    };

    ws.onclose = function () {
      console.log("close connect");
    };
  } else {
    alert("您的浏览器不支持 WebSocket!");
  }

  function send() {
    ws.send(document.getElementById("input").value + ": " + document.getElementById("message").value);
  }
</script>

</head>
<body>
当前用户: <input id="input"/><br/>
<a href="#" rel="external nofollow" onclick="send();">发送消息</a>: <input id="message"/>
<div id="messageDiv"></div>
</body>
</html>

即可实现简单的通信功能

上一篇:Kotlin 单例实例详解

栏    目:JAVA代码

下一篇:java ArrayList.remove()的三种错误用法以及六种正确用法详解

本文标题:Springboot基于websocket实现简单在线聊天功能

本文地址:http://www.codeinn.net/misctech/24433.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有