首页新闻招聘找找看知识库
  • 浏览:8 2020-05-20 17:39 来自 cn2020


    websocket
    #####http://localhost:8080/websocket/index
    ##########################################
    ##########################################
    ##########################################
    1、pom.xml

    <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>
    <!-- 模板引擎 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    2、SpringApplication

    @EnableWebSocket
    @SpringBootApplication
    public class WxdemoApplication {

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

      @Bean
      public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
      }

    }

    3、WebsocketEndpoint

    @Component
    @ServerEndpoint(value ="/websocket")
    public class WebsocketEndpoint {
      //存放该服务器该ws的所有连接。用处:比如向所有连接该ws的用户发送通知消息。
      private static CopyOnWriteArraySet<WebsocketEndpoint> sessions = new CopyOnWriteArraySet<>();

      private Session session;

      @OnOpen
      public void onOpen(Session session){
        System.out.println("java websocket:打开连接");
        this.session = session;
        sessions.add(this);
      }

      @OnClose
      public void onClose(Session session){
        System.out.println("java websocket:关闭连接");
        sessions.remove(this);
      }

      @OnMessage
      public void onMessage(Session session,String message) throws IOException {
        System.out.println("java websocket 收到消息:"+message);
        session.getBasicRemote().sendText("后台接收到您发的消息:"+message);
      }

      @OnError
      public void onError(Session session,Throwable error){
        System.out.println("java websocket 出现错误");
      }

      public Session getSession() {
        return session;
      }

      public void setSession(Session session) {
        this.session = session;
      }

    }


    4、application.properties


    #thymeleaf配置
    #是否启用模板缓存。
    spring.thymeleaf.cache=false
    #是否为Web框架启用Thymeleaf视图解析。
    spring.thymeleaf.enabled=true
    #在SpringEL表达式中启用SpringEL编译器。
    spring.thymeleaf.enable-spring-el-compiler=true
    #模板文件编码。
    spring.thymeleaf.encoding=UTF-8
    #要应用于模板的模板模式。另请参见Thymeleaf的TemplateMode枚举。
    spring.thymeleaf.mode=HTML5
    #在构建URL时添加前缀以查看名称的前缀。
    spring.thymeleaf.prefix=classpath:/templates/
    #Content-Type写入HTTP响应的值。
    spring.thymeleaf.servlet.content-type=text/html
    #在构建URL时附加到视图名称的后缀。
    spring.thymeleaf.suffix=.html


    5、thymeleaf
    ######resources/websocket/index.html


    <!doctype html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="utf-8"></meta>
    <title>websocket</title>
    </head>
    <body>
    hello websocket<br/>
    <input id="input_id" type="text" /><button onclick="sendMessage()">发送</button>
    <button onclick="closeWebsocket()">关闭</button>
    <div id="message_id"></div>
    </body>
    <script type="text/javascript">
    document.getElementById('input_id').focus();
    var websocket = null;
    //当前浏览前是否支持websocket
    if("WebSocket" in window){
    var url = "ws://127.0.0.1:8080/websocket";
    websocket = new WebSocket(url);
    }else{
    alert("浏览器不支持websocket");
    }

    websocket.onopen = function(event){
    setMessage("打开连接");
    }

    websocket.onclose = function(event){
    setMessage("关闭连接");
    }

    websocket.onmessage = function(event){
    setMessage(event.data);
    }

    websocket.onerror = function(event){
    setMessage("连接异常");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
    closeWebsocket();
    }

    //关闭websocket
    function closeWebsocket(){
    //3代表已经关闭
    if(3!=websocket.readyState){
    websocket.close();
    }else{
    alert("websocket之前已经关闭");
    }
    }

    //将消息显示在网页上
    function setMessage(message){
    document.getElementById('message_id').innerHTML += message + '<br/>';
    }

    //发送消息
    function sendMessage(){
    //1代表正在连接
    if(1==websocket.readyState){
    var message = document.getElementById('input_id').value;
    setMessage(message);
    websocket.send(message);
    }else{
    alert("websocket未连接");
    }
    document.getElementById('input_id').value="";
    document.getElementById('input_id').focus();
    }
    </script>
    </html>

    6、Controller
    #####http://localhost:8080/websocket/index

      @RequestMapping("websocket")
      @Controller
      public class WebsocketController {

        private static final String INDEX = "websocket/index";

        @RequestMapping("index")
        public ModelAndView index(){
          return new ModelAndView(INDEX);
        }
    }

登录后才能评论,请先登录注册