`

spring boot Websocket

阅读更多

使用websocket有两种方式:1是使用sockjs,2是使用h5的标准。使用Html5标准自然更方便简单,所以记录的是配合h5的使用方法。

1、pom

  核心是@ServerEndpoint这个注解。这个注解是Javaee标准里的注解,tomcat7以上已经对其进行了实现,如果是用传统方法使用tomcat发布项目,只要在pom文件中引入javaee标准即可使用。

复制代码
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
      <scope>provided</scope>
    </dependency>
复制代码

  但使用springboot的内置tomcat时,就不需要引入javaee-api了,spring-boot已经包含了。使用springboot的websocket功能首先引入springboot组件。

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

  顺便说一句,springboot的高级组件会自动引用基础的组件,像spring-boot-starter-websocket就引入了spring-boot-starter-web和spring-boot-starter,所以不要重复引入。

2、使用@ServerEndpoint创立websocket endpoint

  首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。

复制代码
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
复制代码

  接下来就是写websocket的具体实现类,很简单,直接上代码:

复制代码
复制代码
@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage(CommonConstant.CURRENT_WANGING_NUMBER.toString());
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

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

        //群发消息
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}
复制代码
复制代码

使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。

虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。

3、前端代码

   

复制代码
<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8084/websocket");
    }
    else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

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

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

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>
复制代码

 

  4、总结

  springboot已经做了深度的集成和优化,要注意是否添加了不需要的依赖、配置或声明。由于很多讲解组件使用的文章是和spring集成的,会有一些配置,在使用springboot时,由于springboot已经有了自己的配置,再这些配置有可能导致各种各样的异常。

 

http://www.cnblogs.com/bianzy/p/5822426.html

 

分享到:
评论

相关推荐

    spring boot websocket例子

    spring boot websocket例子,实现socket连接,关闭,发送消息功能,运行Application.java运行项目,访问地址http://localhost:8080/socket.html

    [课堂课件讲解]Java微服务实践-Spring Boot WebSocket.pptx

    [课堂课件讲解]Java微服务实践-Spring Boot WebSocket.pptx

    spring boot+websocket前后端简单demo

    在本文中,我们将深入探讨如何使用Spring Boot和WebSocket技术创建一个简单的前后端交互示例。Spring Boot是Java领域中广泛使用的微服务框架,它简化了Spring应用的初始设置和配置。而WebSocket则是一种在客户端和...

    spring boot websocket , mongoDBd存文件 图片服务器

    在本文中,我们将深入探讨如何使用Spring Boot构建一个WebSocket服务器,并与MongoDB集成,特别是利用GridFS存储文件,包括图片。此外,我们还将讨论非GridFS的文件存储方式及其限制。 首先,Spring Boot是一个简化...

    Springboot多连接池+websocket

    在Spring Boot中,可以通过`spring-websocket`模块实现WebSocket功能。使用`@ServerEndpoint`注解定义WebSocket的端点,`@MessageMapping`用于处理消息。同时,还需要配置WebSocket的消息处理器,例如使用`...

    spring boot+vue+websocket带token身份认证推送消息实现

    vue前端后端分离spring boot 2.0集成websocket,带身份认证实现消息推送功能

    Spring boot 2基于Netty的高性能Websocket服务器(心跳模式) 页面

    此资源为websocket的页面源码,配合Spring boot 2基于Netty的高性能Websocket服务器(心跳模式) 文章来使用

    Spring Boot整合websocket实现群聊,点对点聊天,图片发送,音频发送

    Spring Boot作为Java生态中的微服务框架,提供了方便地集成WebSocket的功能,使得开发者能够轻松构建实时交互的应用,如群聊、点对点聊天以及发送图片和音频等富媒体消息。 首先,集成WebSocket到Spring Boot项目中...

    java开发基于SpringBoot+WebSocket+Redis分布式即时通讯群聊系统.zip

    一个基于Spring Boot + WebSocket + Redis,可快速开发的分布式即时通讯群聊系统。适用于直播间聊天、游戏内聊天、客服聊天等临时性群聊场景。 Java开发基于SpringBoot+WebSocket+Redis分布式即时通讯群聊系统。一...

    38. Spring Boot分布式Session状态保存Redis【从零开始学Spring Boot】

    在Spring Boot应用中,随着系统复杂度的增加,单一服务器往往无法满足高并发、高可用的需求,因此我们会采用分布式架构。然而,在分布式环境下,传统的基于HTTP Session的状态管理方式会遇到问题,因为每个服务器都...

    spring boot webSocket

    本项目是关于如何在Spring Boot 2.0环境下集成WebSocket和STOMP(Simples Text Oriented Messaging Protocol)来实现广播通信和一对一通信的聊天功能。 首先,让我们深入理解WebSocket。WebSocket协议在HTML5中被...

    spring boot+websocket

    在本文中,我们将深入探讨如何在Spring Boot框架中集成WebSocket技术,以便实现实时通信功能。结合jQuery在前端的应用,可以构建出一个高效、实时的Web应用。首先,让我们了解Spring Boot和WebSocket的基本概念。 ...

    spring-boot-websocket-chat-demo:具有SockJS后备和STOMP协议的Spring Boot WebSocket聊天演示

    Spring Boot WebSocket聊天应用程序您可以在签出应用程序的实时版本。要求Java-1.8.x Maven-3.xx设定步骤1.克隆应用程序git clone https://github.com/callicoder/spring-boot-websocket-chat-demo.git 2.使用maven...

    spring-boot-websocket-client代码示例

    在本文中,我们将深入探讨如何使用Spring Boot构建一个WebSocket客户端。`spring-boot-websocket-client`这个项目就是一个关于此主题的代码示例。Spring Boot作为Java生态中的一个热门框架,简化了创建独立、生产...

    WebSocket示例:带有Android客户端和浏览器客户端的Spring Boot WebSocket服务器

    Spring Boot WebSocket和Android客户端Spring Boot WebSocket服务器,具有浏览器客户端和简单的Android客户端。 Android客户端使用来在Android上实现协议 ,以向服务器订阅或发送消息。介绍服务器现在包括三个端点以...

    springboot+websocket实时聊天系统

    springboot+websocket+mysql,实现实时聊天系统,简单demo。包括login 登录页、register 注册页、friend_list 好友列表、message_conver聊天视图 四个页面。

    spring boot 42讲配套源码.zip

    第 2-10 课: 使用 Spring Boot WebSocket 创建聊天室/spring-boot-websocket 第 2-2 课 Spring Boot 项目中使用 JSP/spring-boot-jsp 第 2-3 课 模板引擎 Thymeleaf 基础使用/spring-boot-thymeleaf 第 2-4 课 ...

    spring+websocketdemo

    1. **Spring WebSocket集成**:在Spring Boot项目中,可以通过添加`spring-boot-starter-websocket`依赖来启用WebSocket支持。然后,在配置类中配置WebSocket消息代理,包括设置STOMP(简单消息传输协议)作为消息...

    SpringBoot整合websocket实现数据实时推送

    通过呆着读者手写速成版本的websocket入门案例,以项目案例的方式带你体验websocket的使用场景和相关知识内容。 适合人群:具备一定的开发能力和编程基础,工作1-3年的研发人员 能学到什么: 1.SpringBoot项目的框架...

    关于Spring Boot WebSocket整合以及nginx配置详解

    主要给大家介绍了关于Spring Boot WebSocket整合以及nginx配置的相关资料,文中通过示例代码给大家介绍的非常详细,相信对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习下吧。

Global site tag (gtag.js) - Google Analytics