Netty实现udp发送消息给指定客户端

1、客户端session

package com.pojo.prj.udp;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.net.InetSocketAddress;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Session implements Serializable {

    //设备id
    private String deviceId;

    //设备类型
    private String deviceType;
    // 设备类型:设备id
    private String key;

    //客户端地址和端口
    private InetSocketAddress sender;

}

2、session工具类

package com.pojo.prj.udp;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtil {
    private static final Map deviceIdChannelMap = new ConcurrentHashMap<>();

    private static final Map deviceIdSessionMap = new ConcurrentHashMap<>();

    public static void bindSession(Session session, Channel channel) {
        deviceIdChannelMap.put(session.getKey(), channel);
        deviceIdSessionMap.put(session.getKey(), session);
    }

    public static void unBindSession(String key) {
        deviceIdChannelMap.remove(key);
        deviceIdSessionMap.remove(key);
    }

    public static Session getSession(String key) {
        return deviceIdSessionMap.get(key);
    }

    public static Channel getChannel(String key) {
        return deviceIdChannelMap.get(key);
    }
}

3、udp服务端启动类

你可能感兴趣的:(netty,udp,java,servlet)