spring boot集成Websocket

websocket实现后台像前端主动推送消息的模式,可以减去前端的请求获取数据的模式。而后台主动推送消息一般都是要求消息回馈比较及时,同时减少前端ajax轮询请求,减少资源开销。

spring boot已经集成了websocket,tomcat亦是如此。所以WebSocketConfig配置类就不需要了,不需要开启什么支持,本来就支持。

一、Websocket单机版,有纪念意义。刚开始我就是用这个来应对多用户,结果可想而知。新手注意此坑,实际项目中肯定是有多个用户的。

/**
 * @Auther: lanhaifeng
 * @Date: 2018/11/6 0006 17:59
 * @Description:
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 * @ServerEndpoint 可以把当前类变成websocket服务类
 */
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
    private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    public static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //接收sid
    private String sid="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        logger.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
            sendMessage("连接成功,服务器消息");
        } catch (IOException e) {
            logger.error("websocket IO异常");
        }
    }

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

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("收到来自窗口"+sid+"的信息:"+message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发生错误"+error.getStackTrace());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
        logger.info("推送消息到窗口"+sid+",推送内容:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的,为null则全部推送
                if(sid==null) {
                    item.sendMessage(message);
                }else if(item.sid.equals(sid)){
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    // 移除Socket会话
    private void removeSession(WebSocketSession session) {
        webSocketSet.remove(this);
    }


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

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

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


    public Session getSession() {
        return session;
    }

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

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }
}

二、websocket多线程。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
* @Auther: lanhaifeng
* @Date: 2018/11/6 0006 17:59
* @Description: websocket服务端
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
* @ServerEndpoint 可以把当前类变成websocket服务类
*/
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {

private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
public static int onlineCount = 0;
//存储连接用户的session
private static Map<String, Session> connections = new HashMap<>();


/**
* 打开连接
* @param session
* @param sid
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
connections.put(sid, session);
addOnlineCount();
}

/**
* 接收消息
* @param text
*/
@OnMessage
public void onMessage(String text) {
logger.info("收到来新的信息:"+text);
}

/**
* 异常处理
* @param throwable
*/
@OnError
public void onError(Throwable throwable) {
throwable.printStackTrace();
}

/**
* 关闭连接
* @param sid
*/
@OnClose
public void onClosing(@PathParam("sid") String sid) throws IOException {
connections.remove(sid);
subOnlineCount();
}


/**
* 根据IP发送消息
* @param sid
* @param text
*/
public void sendInfo(@PathParam("sid") String sid,String text) {
try {
Session session = connections.get(sid);
if (session != null && session.isOpen()) {
session.getAsyncRemote().sendText(text);
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 遍历群发消息
* @param text
*/
public void send(String text) {
for (Map.Entry<String, Session> entry : connections.entrySet()) {
sendInfo(entry.getKey(), text);
}
}

/**
* 增加在线人数
*/
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}

/**
* 减少在线人数
*/
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}

猜你喜欢

转载自www.cnblogs.com/zeussbook/p/10899630.html