use of java.nio.channels.DatagramChannel in project xian by happyyangyuan.
the class GelfUDPSender method connect.
protected void connect() throws IOException {
if (isConnected()) {
return;
}
if (channel() == null) {
setChannel(DatagramChannel.open());
} else if (!channel().isOpen()) {
Closer.close(channel());
setChannel(DatagramChannel.open());
}
channel().configureBlocking(false);
InetSocketAddress inetSocketAddress = new InetSocketAddress(getHost(), getPort());
try {
DatagramChannel connect = channel().connect(inetSocketAddress);
setChannel(connect);
} catch (SocketException e) {
reportError(e.getMessage(), e);
}
}
use of java.nio.channels.DatagramChannel in project pi314.notes by pi314.
the class ToyVpnService method run.
private boolean run(InetSocketAddress server) throws Exception {
DatagramChannel tunnel = null;
boolean connected = false;
try {
// Create a DatagramChannel as the VPN tunnel.
tunnel = DatagramChannel.open();
// Protect the tunnel before connecting to avoid loopback.
if (!protect(tunnel.socket())) {
throw new IllegalStateException("Cannot protect the tunnel");
}
// Connect to the server.
tunnel.connect(server);
// For simplicity, we use the same thread for both reading and
// writing. Here we put the tunnel into non-blocking mode.
tunnel.configureBlocking(false);
// Authenticate and configure the virtual network interface.
handshake(tunnel);
// Now we are connected. Set the flag and show the message.
connected = true;
mHandler.sendEmptyMessage(R.string.connected);
// Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
// Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
// We use a timer to determine the status of the tunnel. It
// works on both sides. A positive value means sending, and
// any other means receiving. We start with receiving.
int timer = 0;
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
// Write the outgoing packet to the tunnel.
packet.limit(length);
tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
// If we were receiving, switch to sending.
if (timer < 1) {
timer = 1;
}
}
// Read the incoming packet from the tunnel.
length = tunnel.read(packet);
if (length > 0) {
// Ignore control messages, which start with zero.
if (packet.get(0) != 0) {
// Write the incoming packet to the output stream.
out.write(packet.array(), 0, length);
}
packet.clear();
// There might be more incoming packets.
idle = false;
// If we were sending, switch to receiving.
if (timer > 0) {
timer = 0;
}
}
// fraction of time to avoid busy looping.
if (idle) {
Thread.sleep(100);
// Increase the timer. This is inaccurate but good enough,
// since everything is operated in non-blocking mode.
timer += (timer > 0) ? 100 : -100;
// heartbeat
if (timer < -15000) {
// Send empty control messages.
packet.put((byte) 0).limit(1);
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
// Switch to sending.
timer = 1;
}
// We are sending for a long time but not receiving.
if (timer > 20000) {
throw new IllegalStateException("Timed out");
}
}
}
} catch (InterruptedException e) {
throw e;
} catch (Exception e) {
Log.e(TAG, "Got " + e.toString());
} finally {
try {
tunnel.close();
} catch (Exception e) {
// ignore
}
}
return connected;
}
use of java.nio.channels.DatagramChannel in project xian by happyyangyuan.
the class GelfUDPSender method initiateChannel.
private DatagramChannel initiateChannel() throws IOException {
DatagramChannel resultingChannel = DatagramChannel.open();
resultingChannel.socket().bind(new InetSocketAddress(0));
resultingChannel.connect(new InetSocketAddress(this.host, this.port));
resultingChannel.configureBlocking(false);
return resultingChannel;
}
use of java.nio.channels.DatagramChannel in project xian by happyyangyuan.
the class GraylogUdpConnPool method initiateChannel.
private DatagramChannel initiateChannel() throws IOException {
DatagramChannel resultingChannel = DatagramChannel.open();
resultingChannel.socket().bind(new InetSocketAddress(0));
resultingChannel.connect(new InetSocketAddress(this.host, port));
resultingChannel.configureBlocking(false);
return resultingChannel;
}
use of java.nio.channels.DatagramChannel in project reactor-netty by reactor.
the class UdpServerTests method supportsReceivingDatagrams.
@Test
@Ignore
public void supportsReceivingDatagrams() throws InterruptedException {
final int port = SocketUtils.findAvailableUdpPort();
final CountDownLatch latch = new CountDownLatch(4);
final NettyContext server = UdpServer.create(port).newHandler((in, out) -> {
in.receive().asByteArray().log().subscribe(bytes -> {
if (bytes.length == 1024) {
latch.countDown();
}
});
return Flux.never();
}).doOnSuccess(v -> {
try {
DatagramChannel udp = DatagramChannel.open();
udp.configureBlocking(true);
udp.connect(new InetSocketAddress(InetAddress.getLocalHost(), port));
byte[] data = new byte[1024];
new Random().nextBytes(data);
for (int i = 0; i < 4; i++) {
udp.write(ByteBuffer.wrap(data));
}
udp.close();
} catch (IOException e) {
e.printStackTrace();
}
}).block(Duration.ofSeconds(30));
assertThat("latch was counted down", latch.await(10, TimeUnit.SECONDS));
server.dispose();
}
Aggregations