All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.acgist.snail.net.UdpClient Maven / Gradle / Ivy

package com.acgist.snail.net;

import java.net.InetSocketAddress;
import java.nio.channels.DatagramChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.acgist.snail.system.exception.NetException;

/**
 * 

UDP客户端

*

UDP客户端、服务端通道都是公用一个:

*
    *
  • 单例
  • *
  • UDP通道使用服务器通道
  • *
* * @author acgist * @since 1.0.0 */ public abstract class UdpClient extends ClientMessageHandlerAdapter implements UdpChannel { private static final Logger LOGGER = LoggerFactory.getLogger(UdpClient.class); /** * 客户端名称 */ private final String name; /** * 远程地址 */ protected final InetSocketAddress socketAddress; /** * 新建客户端 * * @param name 客户端名称 * @param handler 消息处理器 * @param socketAddress 远程地址 */ public UdpClient(String name, T handler, InetSocketAddress socketAddress) { super(handler); this.name = name; this.socketAddress = socketAddress; this.open(); } /** *

打开客户端

*

随机端口

* * @return 打开状态 */ public abstract boolean open(); /** * 打开客户端 * * @param port 端口 * * @return 打开状态 */ public boolean open(final int port) { DatagramChannel channel = null; try { channel = this.buildUdpChannel(port); } catch (NetException e) { LOGGER.error("打开UDP客户端异常", e); } return open(channel); } /** *

打开客户端

*

客户端和服务端的使用同一个通道

* * @param channel 通道 * * @return 打开状态 * */ public boolean open(DatagramChannel channel) { if(channel == null) { return false; } this.handler.handle(channel, this.socketAddress); return true; } /** *

关闭资源,标记关闭,不能关闭通道。

*

UDP通道只打开一个,程序结束时才能关闭。

*/ @Override public void close() { LOGGER.debug("关闭UDP Client:{}", this.name); super.close(); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy