基于java的websocket实现

本文介绍了一种在基于Tomcat的WebSocket应用中实现用户消息并发发送的方法。通过自定义WebSocket缓存对象并利用读写锁机制,确保了单个用户消息发送的串行化,从而避免了高频消息发送时可能出现的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于tomcat的websocket实现中,如果会针对一个用户高频的发送消息的情况下,websocket自带的异步发送其实一点卵用都没有,所以,没办法,自己控制websocket的并发发送喽,不多说,直接贴代码

1.基础的websocket缓存对象,这个玩意儿每一个用户进来都会生成一个

public class WebSocketMessage {
    
//读写锁
public ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

private Session session;
public ReentrantReadWriteLock getLock() { return lock; } public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } public Long getRoomId() { return roomId; } public void setRoomId(Long roomId) { this.roomId = roomId; }}

2:websocket的实现

@ServerEndpoint(value = "/client/socket/flop/{userId}")
public class WebSocket {

    private static UserMessageDao userMessageDao;

    /**
     * 在线人数
     */
    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 房间信息缓存
     */
    private static ConcurrentHashMap<Long,FlopWebSocketMessage> user_flopWebSocketMessage = new ConcurrentHashMap<>();
    
/**
 * session对应用户id
 */
private static ConcurrentHashMap<Session,Long> session_userId = new ConcurrentHashMap<>();
/** * 获取在线人数 */ public static Integer getOnlineNumber(){return atomicInteger.get();} public static ConcurrentHashMap<Long, RoomMessage> getRoomId_roomMessage() { return roomId_roomMessage; } public static ConcurrentHashMap<Long, EventMessage> getEvent_eventMessage() { return event_eventMessage; } /** * 创建一个连接 * @param session 当前用户session */ @OnOpen public void onOpen(Session session, @PathParam("userId") Long userId){ if (userId != null){ FlopWebSocketMessage flopWebSocketMessage = new FlopWebSocketMessage(); flopWebSocketMessage.setSession(session); user_flopWebSocketMessage.put(userId,flopWebSocketMessage);
session_userId.put(session,userId);atomicInteger.addAndGet(1); FlopWebSocketResultMessage flopWebsocketResultMessage = new FlopWebSocketResultMessage(); flopWebsocketResultMessage.setCode(ResponseCode.OK); flopWebsocketResultMessage.setMessage("链接成功"); sendMessage(userId,JSON.toJSONString(flopWebsocketResultMessage)); System.out.println(userId+"连接成功"); }else { //断开连接 try { session.close(); System.out.println("连接失败"); } catch (IOException e) { e.printStackTrace(); } } } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message,Session session) throws IOException { Long userId = session_userId.get(session); //发送信息接收成功的信息 FlopWebSocketResultMessage flopWebsocketResultMessage = new FlopWebSocketResultMessage(); flopWebsocketResultMessage.setCode(ResponseCode.OK); flopWebsocketResultMessage.setMessage("信息接收成功"); sendMessage(userId,JSON.toJSONString(flopWebsocketResultMessage)); }
/**
 * 给某一个用户集合发送消息
 * @param userIds 用户集合
 * @param message 需要发送的消息
 */
public static void sendMessage(Set<Long> userIds, String message){
    for (Long userId : userIds){
        FlopWebSocketMessage flopWebSocketMessage = user_flopWebSocketMessage.get(userId);
        if (flopWebSocketMessage != null){
            ReentrantReadWriteLock reentrantLock = flopWebSocketMessage.getLock();
            //给这个用户的对象加上读写锁(针对到用户的读写锁,这样多个用户是并发发送消息的,但是单个用户是串行发送消息的)
            reentrantLock.writeLock().lock();
            try {
                flopWebSocketMessage.getSession().getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
                flopWebSocketMessage.getLock().writeLock().unlock();
            }
            flopWebSocketMessage.getLock().writeLock().unlock();
        }
    }
}
/** * 发生错误时调用 * @param error 错误信息 */ @OnError public void onError(Throwable error){ System.out.println("连接错误:"+error.getMessage()); } /** * 连接关闭调用的方法 */ @OnClose public void onClose(Session session){ Long userId = session_userId.get(session); //查找该用户是否有进入房间 if (userId != null && user_flopWebSocketMessage.get(userId) != null){ ReentrantReadWriteLock reentrantLock = user_flopWebSocketMessage.get(userId).getLock(); user_flopWebSocketMessage.remove(userId); reentrantLock.writeLock().unlock(); } session_userId.remove(session); atomicInteger.addAndGet(-1); System.out.println("连接关闭:"+userId); }}

注意:

千万不要在除了onOpen方法外使用@PathParam("userId")从连接的链接中获取携带的参数,绝对回给你意想不到的惊喜

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值