zoukankan      html  css  js  c++  java
  • springBoot 使用webSocket

    本文(2019年6月18日 飞快的蜗牛博客) 

     有许多人走着走着,就迷失了自己,所以不论发生了什么,有时候抱着自己去静下来想想,要好好的对待自己;“钱塘江上潮信来,今日方知我是我”,我信奉这句话,不是我超脱了,是有时我们醒悟了;

    注意标题:springboot使用websocket

      1】第一步:引入依赖:

       <!--集成websocket-->

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

    2】第二步:配置websocket

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

    /**
    *
    * 使用@SpringBootApplication启动类进行启动时需要下面这段代码,****但生成war包部署在tomcat中不需要这段
    * 若打成war包使用tomcat运行的话,则注释掉这个类中serverEndpointExporter 方法.
    *
    */

    @Configuration
    public class WebSocketConfig {


    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
    }
    }
    3】第三步:可以在controller 下写下此类:

    import org.springframework.stereotype.Component;

    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArraySet;

    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;
    /**
    * 即时通讯
    */
    @Component
    @ServerEndpoint("/webSocket")
    public class MyWebScoketController {

    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<MyWebScoketController> webSocketSet = new CopyOnWriteArraySet<MyWebScoketController>();
    private Session session;

    /**
    * 连接建立成功调用的方法
    * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
    */
    @OnOpen
    public void onOpen(Session session){
    this.session = session;
    webSocketSet.add(this); //加入set中
    addOnlineCount(); //在线数加1
    System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }
    /**
    * 连接关闭调用的方法
    */
    @OnClose
    public void onClose(){
    webSocketSet.remove(this); //从set中删除
    subOnlineCount(); //在线数减1
    System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }
    /**
    * 收到客户端消息后调用的方法
    * @param message 客户端发送过来的消息
    * @param session 可选的参数
    */
    @OnMessage
    public void onMessage(String message, Session session) {
    System.out.println("来自客户端的消息:" + message);
    //群发消息
    for(MyWebScoketController item: webSocketSet){
    try {
    item.sendMessage(message);
    } catch (IOException e) {
    e.printStackTrace();
    continue;
    }
    }
    }
    @OnError
    public void onError(Session session, Throwable error){
    System.out.println("发生错误");
    error.printStackTrace();
    }

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

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

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

    public static synchronized void subOnlineCount() {
    MyWebScoketController.onlineCount--;
    }

    }
    4】第四步:在前端写个公共myWebsocket.js 如下
    if("WebSocket" in window){
    console.log("this browser supports websocket...");
    var webSocket=new WebSocket("ws://"+window.location.host+"/XXXX/webSocket");
    }else{
    console.log("this browser does not supports websocket...");
    }
    webSocket.onerror=function(){
    console.log("链接错误...");
    }
    webSocket.onopen=function(){
    console.log("链接成功...");
    }

    /*
    * 哪个页面使用哪个页面加
    * webSocket.onmessage=function(event){
    alert(event);
    }*/
    webSocket.onclose=function(){
    console.log("链接关闭...");
    }
    window.onbeforeunload=function(){
    console.log("窗口即将关闭,准备关闭链接...");
    webSocket.close();
    }
    function webSend(){
    webSocket.send(decodeURIComponent($("#form1").serialize(),true));
    }
    function SendMesaage(mes){
    webSocket.send(mes);
    }
    var closeConn=function(){
    webSocket.close();
    }

    5】第五步:测试 现在页面引入
    <script type="text/javascript" src="static/js/common/myWebSocket.js"></script>

    在发送消息端写下:
    SendMesaage(1300);

    接收端写下:

    webSocket.onmessage=function(event){
      此处可以接收到消息
    }

     

    如果对你有用,觉得好可以给小编打个赏: 

    
    

             






  • 相关阅读:
    深入学习SlidingMenu 2015-06-12 20:27 856人阅读 评论(0) 收藏
    Android 判断SD卡是否存在及容量查询
    第三方登录,授权,分享
    GLSurfaceView用法详解
    Java/android面试题
    SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT'OpenRowset/OpenDatasource' 的访问
    填充数字以达到位数
    web api post
    .net测试方法效率获取系统当前时间
    vs2012更新问题
  • 原文地址:https://www.cnblogs.com/luojiesheng/p/11046161.html
Copyright © 2011-2022 走看看