当前位置: 首页>>代码示例>>Java>>正文


Java DatagramChannel类代码示例

本文整理汇总了Java中java.nio.channels.DatagramChannel的典型用法代码示例。如果您正苦于以下问题:Java DatagramChannel类的具体用法?Java DatagramChannel怎么用?Java DatagramChannel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DatagramChannel类属于java.nio.channels包,在下文中一共展示了DatagramChannel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
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();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:UseDGWithIPv6.java

示例2: JdpBroadcaster

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
/**
 * Create a new broadcaster
 *
 * @param address - multicast group address
 * @param srcAddress - address of interface we should use to broadcast.
 * @param port - udp port to use
 * @param ttl - packet ttl
 * @throws IOException
 */
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
        throws IOException, JdpException {
    this.addr = address;
    this.port = port;

    ProtocolFamily family = (address instanceof Inet6Address)
            ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;

    channel = DatagramChannel.open(family);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);

    // with srcAddress equal to null, this constructor do exactly the same as
    // if srcAddress is not passed
    if (srcAddress != null) {
        // User requests particular interface to bind to
        NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
        try {
            channel.bind(new InetSocketAddress(srcAddress, 0));
        } catch (UnsupportedAddressTypeException ex) {
            throw new JdpException("Unable to bind to source address");
        }
        channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:35,代码来源:JdpBroadcaster.java

示例3: newHandle

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
@Override
protected DatagramChannel newHandle(SocketAddress localAddress) throws Exception {
    DatagramChannel ch = DatagramChannel.open();

    try {
        if (localAddress != null) {
            ch.socket().bind(localAddress);
        }

        return ch;
    } catch (Exception e) {
        // If we got an exception while binding the datagram,
        // we have to close it otherwise we will loose an handle
        ch.close();
        throw e;
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:18,代码来源:NioDatagramConnector.java

示例4: run

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
public void run () {
    if (mIsConnected) return;
    try {
        mChannel = DatagramChannel.open();
        mChannel.configureBlocking(false);
        mChannel.connect(new InetSocketAddress(mAddress, mPort));

        if (mListenerThread == null) {
            mListenerThread = new ListenerThread();
            mListenerThread.start();
            mActivityHandler.sendMessage(composeMessage(MSG_ON_CONNECT, ""));
            mIsConnected = true;
        }

        Looper.prepare();
        mSendHandler = new Handler();
        Looper.loop();

    } catch (Exception e) {
        mActivityHandler.sendMessage(composeMessage(MSG_ON_CONNECTION_FAIL, e.toString()));
    }
}
 
开发者ID:voroshkov,项目名称:Chorus-RF-Laptimer,代码行数:23,代码来源:UDPService.java

示例5: checkSocket

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
/**
     * resolves host, builds socket, returns true if it succeeds
     */
    private boolean checkSocket() {
        if ((channel != null) && channel.isOpen()) { //if(datagramSocket!=null && datagramSocket.isBound()) {
            return true;
        }
        try {
            channel = DatagramChannel.open();
            datagramSocket = channel.socket();
            datagramSocket.setReuseAddress(true);
            // disable timeout so that receive just waits for data forever (until interrupted)
//            datagramSocket.setSoTimeout(TIMEOUT_MS);
//            if (datagramSocket.getSoTimeout() != TIMEOUT_MS) {
//                log.warning("datagram socket read timeout value read=" + datagramSocket.getSoTimeout() + " which is different than timeout value of " + TIMEOUT_MS + " that we tried to set - perhaps timeout is not supported?");
//            }
            SocketAddress address = new InetSocketAddress(getPort());
            datagramSocket.bind(address);
            log.info("bound " + this);
            datagramSocket.setSoTimeout(0); // infinite timeout
            return true;
        } catch (IOException e) {
            log.warning("caught " + e + ", datagramSocket will be constructed later");
            return false;
        }
    }
 
开发者ID:SensorsINI,项目名称:jaer,代码行数:27,代码来源:AEUnicastInput.java

示例6: run

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
public void run() {
    try {
        DatagramChannel dc = DatagramChannel.open();
        ByteBuffer bb = ByteBuffer.allocateDirect(12);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.putInt(1).putLong(1);
        bb.flip();
        InetAddress address = InetAddress.getLocalHost();
        InetSocketAddress isa = new InetSocketAddress(address, port);
        dc.connect(isa);
        clientISA = dc.getLocalAddress();
        dc.write(bb);
    } catch (Exception ex) {
        e = ex;
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:Sender.java

示例7: launchWithDatagramChannel

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
public static DatagramChannel launchWithDatagramChannel(String className, String options[], String args[])
    throws IOException
{
    DatagramChannel dc = DatagramChannel.open();
    dc.socket().bind(new InetSocketAddress(0));

    int port = dc.socket().getLocalPort();
    launch(className, options, args, Util.getFD(dc));
    dc.close();

    dc = DatagramChannel.open();
    InetAddress address = InetAddress.getLocalHost();
    if (address.isLoopbackAddress()) {
        address = InetAddress.getLoopbackAddress();
    }
    InetSocketAddress isa = new InetSocketAddress(address, port);

    dc.connect(isa);
    return dc;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:Launcher.java

示例8: UDPEchoTest

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
private static void UDPEchoTest() throws IOException {
    DatagramChannel dc = Launcher.launchWithDatagramChannel(ECHO_SERVICE, null);

    String msg = "I was out saving the galaxy when your grandfather was in diapers";

    ByteBuffer bb = ByteBuffer.wrap(msg.getBytes("UTF-8"));
    dc.write(bb);

    // and receive the echo
    byte b[] = new byte[msg.length() + 100];
    DatagramPacket pkt2 = new DatagramPacket(b, b.length);
    dc.socket().setSoTimeout(5000);
    dc.socket().receive(pkt2);

    if (pkt2.getLength() != msg.length()) {
        throw new RuntimeException("Received packet of incorrect length");
    }

    dc.close();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:EchoTest.java

示例9: start

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
public synchronized void start() throws IOException {
    if (running) {
        return;
    }
    // Start channel
    DatagramChannel channel = DatagramChannel.open();
    channel.configureBlocking(true);
    channel.socket().bind(new InetSocketAddress(port));
    running = true;
    // Start server thread
    new ServerThread(channel).start();
    log.info("DNS server started");
}
 
开发者ID:DeepAQ,项目名称:CerDNS,代码行数:14,代码来源:DNSServer.java

示例10: open

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
@Override
protected DatagramChannel open(SocketAddress localAddress) throws Exception {
    final DatagramChannel c = DatagramChannel.open();
    boolean success = false;
    try {
        new NioDatagramSessionConfig(c).setAll(getSessionConfig());
        c.configureBlocking(false);
        c.socket().bind(localAddress);
        c.register(selector, SelectionKey.OP_READ);
        success = true;
    } finally {
        if (!success) {
            close(c);
        }
    }

    return c;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:19,代码来源:NioDatagramAcceptor.java

示例11: isReadable

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
@Override
protected boolean isReadable(DatagramChannel handle) {
    SelectionKey key = handle.keyFor(selector);

    if ((key == null) || (!key.isValid())) {
        return false;
    }

    return key.isReadable();
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:11,代码来源:NioDatagramAcceptor.java

示例12: isWritable

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
@Override
protected boolean isWritable(DatagramChannel handle) {
    SelectionKey key = handle.keyFor(selector);

    if ((key == null) || (!key.isValid())) {
        return false;
    }

    return key.isWritable();
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:11,代码来源:NioDatagramAcceptor.java

示例13: localAddress

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
@Override
protected SocketAddress localAddress(DatagramChannel handle) throws Exception {
    InetSocketAddress inetSocketAddress = (InetSocketAddress) handle.socket().getLocalSocketAddress();
    InetAddress inetAddress = inetSocketAddress.getAddress();

    if ((inetAddress instanceof Inet6Address) && (((Inet6Address) inetAddress).isIPv4CompatibleAddress())) {
        // Ugly hack to workaround a problem on linux : the ANY address is always converted to IPV6
        // even if the original address was an IPV4 address. We do store the two IPV4 and IPV6
        // ANY address in the map.
        byte[] ipV6Address = ((Inet6Address) inetAddress).getAddress();
        byte[] ipV4Address = new byte[4];

        for (int i = 0; i < 4; i++) {
            ipV4Address[i] = ipV6Address[12 + i];
        }

        InetAddress inet4Adress = Inet4Address.getByAddress(ipV4Address);
        return new InetSocketAddress(inet4Adress, inetSocketAddress.getPort());
    } else {
        return inetSocketAddress;
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:23,代码来源:NioDatagramAcceptor.java

示例14: close

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
@Override
protected void close(DatagramChannel handle) throws Exception {
    SelectionKey key = handle.keyFor(selector);

    if (key != null) {
        key.cancel();
    }

    handle.disconnect();
    handle.close();
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:12,代码来源:NioDatagramAcceptor.java

示例15: sendAck

import java.nio.channels.DatagramChannel; //导入依赖的package包/类
/**
 * 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());
    }
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:34,代码来源:NioReplicationTask.java


注:本文中的java.nio.channels.DatagramChannel类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。