下面列出了java.nio.channels.DatagramChannel#read() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
}
}
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");
}
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");
}
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);
}
}
/**
* @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
}
}
/**
* @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
}
}
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);
}
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;
}