下面列出了java.nio.channels.UnsupportedAddressTypeException#java.nio.channels.DatagramChannel 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void start(Collection<DHT> dhts, ConfigReader config) {
try {
channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, 1);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
// we only need to send, not to receive, so need to bind to a specific port
channel.bind(new InetSocketAddress(0));
channel.connect(new InetSocketAddress(InetAddress.getByAddress(new byte[] {(byte) 224,0,23,5}), 9696));
} catch (IOException e) {
e.printStackTrace();
return;
}
t.setDaemon(true);
t.setName("opentracker-sync");
t.start();
// OT-sync only supports ipv4 atm
dhts.stream().filter(d -> d.getType().PREFERRED_ADDRESS_TYPE == Inet4Address.class).forEach(d -> {
d.addIncomingMessageListener(this::incomingPacket);
});
}
public static void main(String[] args) throws Exception {
ch = DatagramChannel.open();
ch.bind(new InetSocketAddress(5555));
ch.configureBlocking(false);
Executor pool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
pool.execute(DatagramTest::sendLoop);
}
System.out.println("Warming up...");
Thread.sleep(3000);
totalPackets.set(0);
System.out.println("Benchmarking...");
Thread.sleep(5000);
System.out.println(totalPackets.get() / 5);
System.exit(0);
}
public static void main(String[] args) throws IOException
{
ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
DatagramChannel dgChannel = DatagramChannel.open();
for(int i = 0; i < targets.length; i++){
data.rewind();
SocketAddress sa = new InetSocketAddress(targets[i], port);
System.out.println("-------------\nDG_Sending data:" +
"\n remaining:" + data.remaining() +
"\n position:" + data.position() +
"\n limit:" + data.limit() +
"\n capacity:" + data.capacity() +
" bytes on DG channel to " + sa);
try {
int n = dgChannel.send(data, sa);
System.out.println("DG_Sent " + n + " bytes");
} catch (IOException e) {
//This regression test is to check vm crash only, so ioe is OK.
e.printStackTrace();
}
}
dgChannel.close();
}
protected void configureListenerChannel() {
// open the listener port
try {
listenerChannel = DatagramChannel.open();
listenerChannel.socket().bind(new InetSocketAddress(listenerPort));
listenerChannel.configureBlocking(false);
logger.info("Listening for incoming data on {}", listenerChannel.getLocalAddress());
synchronized (selector) {
selector.wakeup();
try {
listenerKey = listenerChannel.register(selector, listenerChannel.validOps());
} catch (ClosedChannelException e1) {
logger.warn("An exception occurred while registering a selector: {}", e1.getMessage());
}
}
} catch (Exception e3) {
logger.warn("An exception occurred while creating the Listener Channel on port number {} ({})",
listenerPort, e3.getMessage());
}
}
public void open(SocketAddress localSocketAddress, DatagramHandler handler) throws Exception
{
// Create a non-blocking socket channel
DatagramChannel channel = DatagramChannel.open();
// read all properties for the UDP socket
Config.getConfigForUDPSocket(channel.socket());
channel.socket().bind(localSocketAddress);
channel.configureBlocking(false);
synchronized(selectorLock)
{
this.selector.wakeup();
handler.init(channel.register(selector, SelectionKey.OP_READ, handler));
}
}
public static void main(String[] args) throws IOException
{
ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
DatagramChannel dgChannel = DatagramChannel.open();
for(int i = 0; i < targets.length; i++){
data.rewind();
SocketAddress sa = new InetSocketAddress(targets[i], port);
System.out.println("-------------\nDG_Sending data:" +
"\n remaining:" + data.remaining() +
"\n position:" + data.position() +
"\n limit:" + data.limit() +
"\n capacity:" + data.capacity() +
" bytes on DG channel to " + sa);
try {
int n = dgChannel.send(data, sa);
System.out.println("DG_Sent " + n + " bytes");
} catch (IOException e) {
//This regression test is to check vm crash only, so ioe is OK.
e.printStackTrace();
}
}
dgChannel.close();
}
public static void main(String[] args) throws IOException
{
ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
DatagramChannel dgChannel = DatagramChannel.open();
for(int i = 0; i < targets.length; i++){
data.rewind();
SocketAddress sa = new InetSocketAddress(targets[i], port);
System.out.println("-------------\nDG_Sending data:" +
"\n remaining:" + data.remaining() +
"\n position:" + data.position() +
"\n limit:" + data.limit() +
"\n capacity:" + data.capacity() +
" bytes on DG channel to " + sa);
try {
int n = dgChannel.send(data, sa);
System.out.println("DG_Sent " + n + " bytes");
} catch (IOException e) {
//This regression test is to check vm crash only, so ioe is OK.
e.printStackTrace();
}
}
dgChannel.close();
}
protected void startNIOServer() throws Exception {
SelectableChannel server = null;
int interestKey;
//1. Start reactor service
selectorManager.start();
//2. Start server on the specified port
if (this.udpMode) {
server = DatagramChannel.open();
((DatagramChannel) server).socket().bind(new InetSocketAddress(host, port));
interestKey = SelectionKey.OP_READ;
} else {
server = ServerSocketChannel.open();
((ServerSocketChannel) server).socket().bind(new InetSocketAddress(host, port), 1024);
interestKey = SelectionKey.OP_ACCEPT;
}
server.configureBlocking(false);
//3. Choose one reactor to handle NIO event
selectorManager.getReactor(0).registerChannel(server, interestKey);
System.out.println("INFO: NAMI Server started on port " + String.valueOf(port) + "...");
}
public long transferTo(DatagramChannel ch, SocketAddress raddr) throws IOException {
int send = 0;
for (ByteBuffer buf: buffers) {
if (buf.hasRemaining()) {
int w = ch.send(buf, raddr);
if (w == 0) {
break;
} else {
send += w;
}
}
}
written += send;
return send;
}
public void testReadWrite_Block_WriterNotBound() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
DatagramChannel dc = DatagramChannel.open();
// The writer isn't bound, but is connected.
dc.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));
// Connect channel2 after data has been written.
channel2.connect(dc.socket().getLocalSocketAddress());
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
closeBlockedReaderChannel2(targetBuf);
dc.close();
}
@Override
public void open() throws IOException {
if (channel == null) {
channel = DatagramChannel.open();
if (maxSendBufferSize > 0) {
channel.setOption(StandardSocketOptions.SO_SNDBUF, maxSendBufferSize);
final int actualSendBufSize = channel.getOption(StandardSocketOptions.SO_SNDBUF);
if (actualSendBufSize < maxSendBufferSize) {
logger.warn("Attempted to set Socket Send Buffer Size to " + maxSendBufferSize
+ " bytes but could only set to " + actualSendBufSize + "bytes. You may want to "
+ "consider changing the Operating System's maximum receive buffer");
}
}
}
if (!channel.isConnected()) {
channel.connect(new InetSocketAddress(InetAddress.getByName(host), port));
}
}
public static void main(String[] args) throws IOException
{
ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
DatagramChannel dgChannel = DatagramChannel.open();
for(int i = 0; i < targets.length; i++){
data.rewind();
SocketAddress sa = new InetSocketAddress(targets[i], port);
System.out.println("-------------\nDG_Sending data:" +
"\n remaining:" + data.remaining() +
"\n position:" + data.position() +
"\n limit:" + data.limit() +
"\n capacity:" + data.capacity() +
" bytes on DG channel to " + sa);
try {
int n = dgChannel.send(data, sa);
System.out.println("DG_Sent " + n + " bytes");
} catch (IOException e) {
//This regression test is to check vm crash only, so ioe is OK.
e.printStackTrace();
}
}
dgChannel.close();
}
/** {@inheritDoc} */
@Override
public Closeable registerChannel(String name, DatagramChannel channel) {
final ManagedBinding binding = new CloseableManagedBinding(name, (InetSocketAddress) channel.socket().getLocalSocketAddress(), channel, this);
registerBinding(binding);
return binding;
}
/**
* send a reply-acknowledgement (6,2,3), sends it doing a busy write, the ACK is so small
* that it should always go to the buffer
* @param key
* @param channel
*/
protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) {
try {
ByteBuffer buf = ByteBuffer.wrap(command);
int total = 0;
if (channel instanceof DatagramChannel) {
DatagramChannel dchannel = (DatagramChannel)channel;
//were using a shared channel, document says its thread safe
//TODO check optimization, one channel per thread?
while ( total < command.length ) {
total += dchannel.send(buf, udpaddr);
}
} else {
while ( total < command.length ) {
total += channel.write(buf);
}
}
if (log.isTraceEnabled()) {
log.trace("ACK sent to " +
( (channel instanceof SocketChannel) ?
((SocketChannel)channel).socket().getInetAddress() :
((DatagramChannel)channel).socket().getInetAddress()));
}
} catch ( java.io.IOException x ) {
log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage());
}
}
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
SocketAddress remote = new InetSocketAddress(lh, 1234);
DatagramSocket ds = null;
DatagramChannel dc = null;
try {
ds = new DatagramSocket();
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
check(ds, dc);
ds.connect(remote);
dc.connect(remote);
check(ds, dc);
ds.disconnect();
dc.disconnect();
check(ds, dc);
// repeat tests using socket adapter
ds.connect(remote);
dc.socket().connect(remote);
check(ds, dc);
ds.disconnect();
dc.socket().disconnect();
check(ds, dc);
} finally {
if (ds != null) ds.close();
if (dc != null) dc.close();
}
}
private DatagramChannel createChannel() throws IOException {
logi(TAG, "Open");
DatagramChannel datagramChannel = DatagramChannel.open();
datagramChannel.configureBlocking(false);
datagramChannel.connect(getRewrittenDestination());
return datagramChannel;
}
/** Create UDP channel
*
* @param broadcast Support broadcast?
* @param port Port to use or 0 to auto-assign
* @return UDP channel
* @throws Exception on error
*/
public static DatagramChannel createUDP(boolean broadcast, int port) throws Exception
{
// Current use of multicast addresses works only with INET, not INET6
final DatagramChannel udp = DatagramChannel.open(StandardProtocolFamily.INET);
udp.configureBlocking(true);
if (broadcast)
udp.socket().setBroadcast(true);
udp.socket().setReuseAddress(true);
udp.bind(new InetSocketAddress(port));
return udp;
}
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
SocketAddress remote = new InetSocketAddress(lh, 1234);
DatagramSocket ds = null;
DatagramChannel dc = null;
try {
ds = new DatagramSocket();
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
check(ds, dc);
ds.connect(remote);
dc.connect(remote);
check(ds, dc);
ds.disconnect();
dc.disconnect();
check(ds, dc);
// repeat tests using socket adapter
ds.connect(remote);
dc.socket().connect(remote);
check(ds, dc);
ds.disconnect();
dc.socket().disconnect();
check(ds, dc);
} finally {
if (ds != null) ds.close();
if (dc != null) dc.close();
}
}
@Override
@SuppressWarnings("deprecation")
public boolean isActive() {
DatagramChannel ch = javaChannel();
return ch.isOpen() && (
config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered()
|| ch.socket().isBound());
}
static void wakeupWhenBound(final DatagramChannel dc) {
Runnable wakeupTask = new Runnable() {
public void run() {
try {
// poll for local address
InetSocketAddress local;
do {
Thread.sleep(50);
local = (InetSocketAddress)dc.getLocalAddress();
} while (local == null);
// send message to channel to wakeup receiver
DatagramChannel sender = DatagramChannel.open();
try {
ByteBuffer bb = ByteBuffer.wrap("hello".getBytes());
InetAddress lh = InetAddress.getLocalHost();
SocketAddress target =
new InetSocketAddress(lh, local.getPort());
sender.send(bb, target);
} finally {
sender.close();
}
} catch (Exception x) {
x.printStackTrace();
}
}};
new Thread(wakeupTask).start();
}
public void open(SocketAddress bindAddress, SocketAddress peerAddress) throws IOException {
channel = DatagramChannel.open();
channel.socket().bind(bindAddress);
channel.configureBlocking(false);
channel.connect(peerAddress);
stream = new MAVLinkStream(schema, channel);
stream.setDebug(debug);
}
private static DatagramChannel newSocket(SelectorProvider provider) {
try {
/**
* Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
* {@link SelectorProvider#provider()} which is called by each DatagramChannel.open() otherwise.
*
* See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
*/
return provider.openDatagramChannel();
} catch (IOException e) {
throw new ChannelException("Failed to open a socket.", e);
}
}
@Override
@SuppressWarnings("deprecation")
public boolean isActive() {
DatagramChannel ch = javaChannel();
return ch.isOpen() && (
config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered()
|| ch.socket().isBound());
}
public ArrayList<Channel> getAll(Direction direction, DatagramChannel theDatagramChannel) {
synchronized (this) {
ArrayList<Channel> selectedChannels = new ArrayList<Channel>();
Iterator<C> it = iterator();
while (it.hasNext()) {
C aChannel = it.next();
if (theDatagramChannel.equals(aChannel.channel) && direction.equals(aChannel.direction)) {
selectedChannels.add(aChannel);
}
}
return selectedChannels;
}
}
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
DatagramChannel ch = javaChannel();
DatagramChannelConfig config = config();
RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
ByteBuf data = allocHandle.allocate(config.getAllocator());
allocHandle.attemptedBytesRead(data.writableBytes());
boolean free = true;
try {
ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes());
int pos = nioData.position();
InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData);
if (remoteAddress == null) {
return 0;
}
allocHandle.lastBytesRead(nioData.position() - pos);
buf.add(new DatagramPacket(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()),
localAddress(), remoteAddress));
free = false;
return 1;
} catch (Throwable cause) {
PlatformDependent.throwException(cause);
return -1;
} finally {
if (free) {
data.release();
}
}
}
/**
* 构造函数
* @param parentSocketContext 父 SocketChannel 对象
* @param datagramChannel UDP通信对象
* @param socketAddress SocketAddress 对象
*/
public UdpSocket(SocketContext parentSocketContext, DatagramChannel datagramChannel, InetSocketAddress socketAddress){
try {
this.provider = SelectorProvider.provider();
this.datagramChannel = datagramChannel;
this.copyFrom(parentSocketContext);
this.session = new UdpSession(this, socketAddress);
this.datagramChannel.configureBlocking(false);
this.connectModel = ConnectModel.SERVER;
this.connectType = ConnectType.UDP;
} catch (Exception e) {
Logger.error("Create socket channel failed",e);
}
}
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
SocketAddress remote = new InetSocketAddress(lh, 1234);
DatagramSocket ds = null;
DatagramChannel dc = null;
try {
ds = new DatagramSocket();
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
check(ds, dc);
ds.connect(remote);
dc.connect(remote);
check(ds, dc);
ds.disconnect();
dc.disconnect();
check(ds, dc);
// repeat tests using socket adapter
ds.connect(remote);
dc.socket().connect(remote);
check(ds, dc);
ds.disconnect();
dc.socket().disconnect();
check(ds, dc);
} finally {
if (ds != null) ds.close();
if (dc != null) dc.close();
}
}
public void replace(Direction direction, InetSocketAddress remoteAddress, DatagramChannel channel) {
synchronized (this) {
Iterator<C> it = iterator();
while (it.hasNext()) {
C aChannel = it.next();
if (remoteAddress.equals(aChannel.remote) && direction.equals(aChannel.direction)
&& !channel.equals(aChannel.channel)) {
aChannel.channel = channel;
}
}
}
}
public void testProcessNextCommand() throws Exception {
System.out.println("processNextCommand");
PerfMonMetricGetter instance = new PerfMonMetricGetter(
SigarProxyCache.newInstance(new Sigar(), 500),
new PerfMonWorker(), DatagramChannel.open());
boolean expResult = false;
boolean result = instance.processNextCommand();
assertEquals(expResult, result);
}
public void test_bind_null() throws Exception {
DatagramChannel dc = DatagramChannel.open();
try {
assertNull(dc.socket().getLocalSocketAddress());
dc.socket().bind(null);
InetSocketAddress localAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
assertTrue(localAddress.getAddress().isAnyLocalAddress());
assertTrue(localAddress.getPort() > 0);
} finally {
dc.close();
}
}