Java Code Examples for java.nio.channels.DatagramChannel#read()

The following examples show how to use java.nio.channels.DatagramChannel#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UkcpClientUdpChannel.java    From kcp-netty with MIT License 5 votes vote down vote up
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    DatagramChannel ch = javaChannel();
    ChannelConfig 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();
        int read = ch.read(nioData);
        if (read <= 0) {
            return read;
        }

        allocHandle.lastBytesRead(nioData.position() - pos);
        buf.add(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()));
        free = false;
        return 1;
    } catch (Throwable cause) {
        PlatformDependent.throwException(cause);
        return -1;
    } finally {
        if (free) {
            data.release();
        }
    }
}
 
Example 2
Source File: MyVpnService.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
private void handshake(DatagramChannel tunnel) throws Exception {
    // To build a secured tunnel, we should perform mutual authentication
    // and exchange session keys for encryption. To keep things simple in
    // this demo, we just send the shared secret in plaintext and wait
    // for the server to send the parameters.

    // Allocate the buffer for handshaking.
    ByteBuffer packet = ByteBuffer.allocate(1024);

    // Control messages always start with zero.
    packet.put((byte) 0).put(mSharedSecret).flip();

    // Send the secret several times in case of packet loss.
    for (int i = 0; i < 3; ++i) {
        packet.position(0);
        tunnel.write(packet);
    }
    packet.clear();

    // Wait for the parameters within a limited time.
    for (int i = 0; i < 50; ++i) {
        Thread.sleep(100);

        // Normally we should not receive random packets.
        int length = tunnel.read(packet);
        if (length > 0 && packet.get(0) == 0) {
            configure(new String(packet.array(), 1, length - 1).trim());
            return;
        }
    }
    throw new IllegalStateException("Timed out");
}
 
Example 3
Source File: SmartVpnService.java    From SmartZPN with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void handshake(DatagramChannel tunnel) throws Exception {
    // To build a secured tunnel, we should perform mutual authentication
    // and exchange session keys for encryption. To keep things simple in
    // this demo, we just send the shared secret in plaintext and wait
    // for the server to send the parameters.
    // Allocate the buffer for handshaking.
    ByteBuffer packet = ByteBuffer.allocate(1024);
    if (false){
        // Control messages always start with zero.
        packet.put((byte) 0).put(mSharedSecret).flip();
        // Send the secret several times in case of packet loss.
        for (int i = 0; i < 3; ++i) {
            packet.position(0);
            tunnel.write(packet);
        }
        packet.clear();
    }

    // Wait for the parameters within a limited time.
    for (int i = 0; i < 50; ++i) {
        Thread.sleep(100);
        // Normally we should not receive random packets.
        int length = tunnel.read(packet);
        if (length > 0 && packet.get(0) == 0) {
            configure(new String(packet.array(), 1, length - 1).trim());
            return;
        }
    }
    throw new IllegalStateException("Timed out");
}
 
Example 4
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void readWriteReadData(DatagramChannel sender, byte[] sourceArray,
        DatagramChannel receiver, byte[] targetArray, int dataSize,
        String methodName) throws IOException {
    // write
    ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
    assertEquals(dataSize, sender.write(sourceBuf));

    // read
    ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);

    int count = 0;
    int total = 0;
    long beginTime = System.currentTimeMillis();
    while (total < dataSize && (count = receiver.read(targetBuf)) != -1) {
        total = total + count;
        // 3s timeout to avoid dead loop
        if (System.currentTimeMillis() - beginTime > 3000){
            break;
        }
    }

    assertEquals(dataSize, total);
    assertEquals(targetBuf.position(), total);
    targetBuf.flip();
    targetArray = targetBuf.array();
    for (int i = 0; i < targetArray.length; i++) {
        assertEquals(targetArray[i], (byte) i);
    }
}
 
Example 5
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests DatagramChannel#read(ByteBuffer)
 */
public void test_read_LByteBuffer_closed_nullBuf() throws Exception {
    // regression test for Harmony-754
    ByteBuffer c = null;
    DatagramChannel channel = DatagramChannel.open();
    channel.close();
    try{
        channel.read(c);
        fail("Should throw NullPointerException");
    } catch (NullPointerException e){
        // expected
    }
}
 
Example 6
Source File: DatagramChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests DatagramChannel#read(ByteBuffer)
 */
public void test_read_LByteBuffer_NotConnected_nullBuf() throws Exception {
    // regression test for Harmony-754
    ByteBuffer c = null;
    DatagramChannel channel = DatagramChannel.open();
    try{
        channel.read(c);
        fail("Should throw NullPointerException");
    } catch (NullPointerException e){
        // expected
    }
}
 
Example 7
Source File: NioUdpClient.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void processReadyKey(SelectionKey key) {
  if (!key.isReadable()) {
    silentCloseChannel();
    f.completeExceptionally(new EOFException("channel not readable"));
    pendingTransactions.remove(this);
    return;
  }

  DatagramChannel channel = (DatagramChannel) key.channel();
  ByteBuffer buffer = ByteBuffer.allocate(max);
  int read;
  try {
    read = channel.read(buffer);
    if (read <= 0) {
      throw new EOFException();
    }
  } catch (IOException e) {
    silentCloseChannel();
    f.completeExceptionally(e);
    pendingTransactions.remove(this);
    return;
  }

  buffer.flip();
  byte[] data = new byte[read];
  System.arraycopy(buffer.array(), 0, data, 0, read);
  verboseLog(
      "UDP read",
      channel.socket().getLocalSocketAddress(),
      channel.socket().getRemoteSocketAddress(),
      data);
  silentCloseChannel();
  f.complete(data);
  pendingTransactions.remove(this);
}
 
Example 8
Source File: UdpConnection.java    From kryonet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public InetSocketAddress readFromAddress () throws IOException {
	DatagramChannel datagramChannel = this.datagramChannel;
	if (datagramChannel == null) throw new SocketException("Connection is closed.");
	lastCommunicationTime = System.currentTimeMillis();
	if(!datagramChannel.isConnected())
		return (InetSocketAddress)datagramChannel.receive(readBuffer); // always null on Android >= 5.0
	datagramChannel.read(readBuffer);
	return connectedAddress;
}