SpringBoot是使用socket注解式

这里写图片描述

pom文件

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.turing</groupId>
  <artifactId>springboot_websocket</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springboot_websocket Maven Webapp</name>
  <url>http://maven.apache.org</url>
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.BUILD-SNAPSHOT</version>
  </parent>
    <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>
        <dependency>
          <groupId>javax</groupId>
          <artifactId>javaee-api</artifactId>
          <version>7.0</version>
          <scope>provided</scope>
        </dependency>
    </dependencies>
        <repositories>
            <repository>
                <id>spring-snapshots</id>
                <name>Spring Snapshots</name>
                <url>https://repo.spring.io/libs-snapshot</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
            </repository>
        </repositories>
  <build>
    <finalName>springboot_websocket</finalName>
  </build>
</project>

启动程序application.java

package com.turing.websocket;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@SpringBootApplication
public class Application {
    @RequestMapping("/")
    public String index(){
        System.out.println("启动了");
        return "socket.html";
    }
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

MyWebsocket.java

package com.turing.websocket;


import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

@ServerEndpoint(value = "/websocket")
@Component
public class MyWebsocket {

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        System.out.println("有一连接关闭");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);


    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }



}

WebSocketConfig.java

package com.turing.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

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

}

页面部门

<!DOCTYPE html>
<html>
<head>


    <meta name="content-type" content="text/html; charset=UTF-8">
  <title>WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)</title>
  <style type="text/css">
    #connect-container {
      float: left;
      width: 400px
    }

    #connect-container div {
      padding: 5px;
    }

    #console-container {
      float: left;
      margin-left: 15px;
      width: 400px;
    }

    #console {
      border: 1px solid #CCCCCC;
      border-right-color: #999999;
      border-bottom-color: #999999;
      height: 170px;
      overflow-y: scroll;
      padding: 5px;
      width: 100%;
    }

    #console p {
      padding: 0;
      margin: 0;
    }
  </style>

</head>
<body>

<div>
  <div id="connect-container">
    <input id="radio1" type="radio" name="group1" onclick="updateUrl('/socket/myHandler');">
      <label for="radio1">W3C WebSocket</label>
    <br>
    <input id="radio2" type="radio" name="group1" onclick="updateUrl('/socket/sockjs/myHandler');">
      <label for="radio2">SockJS</label>
    <div>
      <button id="connect" onclick="connect();">链接</button>
      <button id="disconnect" disabled="disabled" onclick="disconnect();">断开</button>
    </div>
    <div>
      <textarea id="message" style="width: 350px" placeholder="输入要发送的消息"></textarea>
    </div>
    <div>
      <button id="echo" onclick="echo();" disabled="disabled">发送消息</button>
    </div>
  </div>
  <div id="console-container">
    <div id="console"></div>
  </div>
</div>
</body>

<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script type="text/javascript">
    var ws = null;
    var url = null;
    var transports = [];

    function setConnected(connected) {
      document.getElementById('connect').disabled = connected;
      document.getElementById('disconnect').disabled = !connected;
      document.getElementById('echo').disabled = !connected;
    }

    //修改url,提供了两种url一种是wbsocket的一种是sockjs的
    function updateUrl(urlPath) {
        //如果链接中有sockjs字段就让链接等于传进来的本身
      if (urlPath.indexOf('sockjs') != -1) {
        url = urlPath;
      }
      else {
        if (window.location.protocol == 'http:') {
          url = 'ws://' + window.location.host + urlPath;
        } else {
          url = 'wss://' + window.location.host + urlPath;
        }
      }
    }


    //链接握手
    function connect() {
      if (!url) {
        alert('选择一个url');
        return;
      }
        //判断链接中是否有sockjs,如果有使用sockjs的方式拼链接,如果没有发送ws链接
      if(url.indexOf('sockjs') != -1){
       //new SockJS(url, _reserved, options);默认三个参数,中间的基本不用,最后一个是sockjs提供的传输功能,参数是数组(默认是全部开启)
         ws =new SockJS(url);
      }else{
         ws= new WebSocket(url);
      }


       //打开链接
      ws.onopen = function () {
        setConnected(true);
        log('消息: 链接已打开');
      };
      //获取消息
      ws.onmessage = function (event) {
      //调用下面的现实信息的方法
        log('推送的消息: ' + event.data);
      };
      //关闭链接
      ws.onclose = function (event) {
        setConnected(false);
         //调用下面的现实信息的方法
        log('消息: 链接已关闭');
        log(event);
      };
    }

    //发送消息
    function echo() {
      if (ws != null) {
      //获取到输入框中的消息
        var message = document.getElementById('message').value;
         //调用下面的现实信息的方法
        log('发送: ' + message);
        ws.send(message);
      } else {
        alert('消息没有链接地址,请重新连接');
      }
    }

    //将传输回来的信息显示在右侧
    function log(message) {
      var console = document.getElementById('console');
      var p = document.createElement('p');
      p.style.wordWrap = 'break-word';
      p.appendChild(document.createTextNode(message));
      console.appendChild(p);
      //防止消息过长干div外面去
      while (console.childNodes.length > 25) {
        console.removeChild(console.firstChild);
      }
      //console.scrollTop = console.scrollHeight;
    }


    //关闭链接的时候将ws链接清空
    function disconnect() {
      if (ws != null) {
        ws.close();
        ws = null;
      }
      setConnected(false);
    }
  </script>
</html>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值