码迷,mamicode.com
首页 > 编程语言 > 详细

项目总结48:Springboot集成Websocket案例

时间:2019-12-13 09:27:55      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:客户端   ogg   logger   session   ack   ssi   void   注解   val   

项目总结48:Springboot集成Websocket案例

 

Springboot集成Websocket的具体实现由很多方式,但原理是一样的;

先放一个具体的案例

  pom.xml jar依赖

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

   服务端发送消息

package com.hs.web.thirdparty.webconnect;

import com.hs.common.util.json.JsonUtil;

import java.util.ArrayList;
import java.util.List;


public class WebConnectionManager {

    private static WebConnectionManager instance = new WebConnectionManager();

    private List<UpdateListener> changeListenerList;

    private WebConnectionManager() {
        changeListenerList = new ArrayList<UpdateListener>();
    }

    public static WebConnectionManager getInstance() {
        return instance;
    }

    public void addChangeListener(UpdateListener changeListener) {
        synchronized (changeListenerList) {
            changeListenerList.add(changeListener);
        }
    }
    
    public void removeChangeListener(UpdateListener changeListener) {
        synchronized (changeListenerList) {
            for (UpdateListener listener : changeListenerList) {
                if (listener.getUid().equals(changeListener.getUid())) {
                    changeListenerList.remove(listener);
                    break;
                }
            }
        }
    }

    public void sendMessage(String message) {
        synchronized (changeListenerList) {
            for (UpdateListener listener : changeListenerList) {
                listener.updateHandle(message);
            }
        }
    }
    
    public void sendMessage(Object obj) {
        //System.out.println("JsonUtil.toJson(obj): " +JsonUtil.toJson(obj));
        sendMessage(JsonUtil.toJson(obj));
    }

    private String getMessage() {
        return null;
    }
    
    public static void main(String[] args) {
    }
    

}

   客户端请求入口

package com.hs.web.thirdparty.webconnect;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.logging.Logger;

@ServerEndpoint(value = "/monitor")
@Component
public class WebSocketServer {
    
    private Session targetSession;
    private UpdateListener changeListener;
    private static final Logger sysLogger = Logger.getLogger("sysLog");

    /**
     *@Description:链接建立成功时调用的方法
     *@param
     *@return  void
     *@author  TangYujie
     *@date  2019/12/12 17:11
     */
    @OnOpen
    public void open(Session session) {
        this.targetSession = session;
        
        changeListener = new UpdateListener() {
            
            @Override
            public String getUid() {
                return targetSession.getId();
            }
            
            @Override
            public void updateHandle(String message) {
                sendMessage(message);
            }
        };
        
        WebConnectionManager.getInstance().addChangeListener(changeListener);
        sysLogger.info("*** WebSocket opened from sessionId " + targetSession.getId());
    }

    /**
     *@Description:收到客户端消息
     *@param
     *@return  void
     *@author  TangYujie
     *@date  2019/12/12 17:13
     */
    @OnMessage
    public void inMessage(String message) {

    }

    /**
     *@Description: 连接关闭
     *@param
     *@return  void
     *@author  TangYujie
     *@date  2019/12/12 17:15
     */
    @OnClose
    public void end() {
        WebConnectionManager.getInstance().removeChangeListener(changeListener);
        sysLogger.info("*** WebSocket closed from sessionId " + this.targetSession.getId());
    }
    
    private synchronized void sendMessage(String message){
        try {
            targetSession.getBasicRemote().sendText(message);
        } catch (IOException e) {
            sysLogger.warning(e.getMessage());
        } catch(IllegalStateException e){
            sysLogger.warning(e.getMessage());
        }
    }
    

}

  监听接口类:一个接口类,定义了updateHandle(数据库处理)和getUid(获取Uid)两个方法

package com.hs.web.thirdparty.webconnect;

public interface UpdateListener {
    
    void updateHandle(String message);
    
    String getUid();

}

  服务端发送消息

    public static void main(String[] args) {
        String data = "this is a test message";
        WebConnectionManager.getInstance().sendMessage(data);
    }

 

 

分析说明:

  1-当客户端通过ws://ip:port/monitor连接socket时,根据@ServerEndpoint(value = "/monitor")注解;执行WebSocketServer 标有@OnOpen的open方法,即建立一个连接;

  2-open方法中会实现一个UpdateListener 接口类,并将该实现加入到WebConnectionManager 中的List<UpdateListener> changeListenerList中;而UpdateListener 接口类中的updateHandle实现了targetSession.getBasicRemote().sendText(message);即服务端的消息推送;

  3-当服务端通过WebConnectionManager.getInstance().sendMessage(data)发送消息时,会遍历List<UpdateListener> changeListenerList,执行其中的updateHandle方法,从而进行消息推送;

项目总结48:Springboot集成Websocket案例

标签:客户端   ogg   logger   session   ack   ssi   void   注解   val   

原文地址:https://www.cnblogs.com/wobuchifanqie/p/12033128.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!