use of java.nio.channels.DatagramChannel in project nifi by apache.
the class ChannelListener method createAndBindDatagramChannel.
private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize) throws IOException {
final DatagramChannel dChannel = DatagramChannel.open();
dChannel.configureBlocking(false);
if (receiveBufferSize > 0) {
dChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
final int actualReceiveBufSize = dChannel.getOption(StandardSocketOptions.SO_RCVBUF);
if (actualReceiveBufSize < receiveBufferSize) {
LOGGER.warn(this + " attempted to set UDP Receive Buffer Size to " + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer");
}
}
dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
dChannel.bind(new InetSocketAddress(nicIPAddress, port));
return dChannel;
}
use of java.nio.channels.DatagramChannel in project nifi by apache.
the class ChannelListener method addDatagramChannel.
/**
* Binds to listen for data grams on the given local IPAddress/port and
* restricts receipt of datagrams to those from the provided host and port,
* must specify both. This improves performance for datagrams coming from a
* sender that is known a-priori.
*
* @param nicIPAddress - if null will listen on wildcard address, which
* means datagrams will be received on all local network interfaces.
* Otherwise, will bind to the provided IP address associated with some NIC.
* @param port - the port to listen on. This is used to provide a well-known
* destination for a sender.
* @param receiveBufferSize - the number of bytes to request for a receive
* buffer from OS
* @param sendingHost - the hostname, or IP address, of the sender of
* datagrams. Only datagrams from this host will be received. If this is
* null the wildcard ip is used, which means datagrams may be received from
* any network interface on the local host.
* @param sendingPort - the port used by the sender of datagrams. Only
* datagrams from this port will be received.
* @throws IOException if unable to add channel
*/
public void addDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize, final String sendingHost, final Integer sendingPort) throws IOException {
if (sendingHost == null || sendingPort == null) {
addDatagramChannel(nicIPAddress, port, receiveBufferSize);
return;
}
final DatagramChannel dChannel = createAndBindDatagramChannel(nicIPAddress, port, receiveBufferSize);
dChannel.connect(new InetSocketAddress(sendingHost, sendingPort));
dChannel.register(socketChannelSelector, SelectionKey.OP_READ);
}
use of java.nio.channels.DatagramChannel in project opennms by OpenNMS.
the class SyslogdImplementationsIT method doTestSyslogd.
private void doTestSyslogd(SyslogReceiver receiver) throws Exception {
Thread listener = new Thread(receiver);
listener.start();
Thread.sleep(3000);
final int eventCount = 100;
List<Integer> foos = new ArrayList<>();
for (int i = 0; i < eventCount; i++) {
int eventNum = Double.valueOf(Math.random() * 10000).intValue();
foos.add(eventNum);
}
m_eventCounter.setAnticipated(eventCount);
String testPduFormat = "2010-08-19 localhost foo%d: load test %d on tty1";
/*
SyslogClient sc = new SyslogClient(null, 10, SyslogClient.LOG_USER, addr("127.0.0.1"));
// Test by directly invoking the SyslogConnection task
System.err.println("Starting to send packets");
final long start = System.currentTimeMillis();
for (int i = 0; i < eventCount; i++) {
int foo = foos.get(i);
DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo));
WaterfallExecutor.waterfall(m_executorService, new SyslogConnection(pkt, m_config));
}
// Test by sending over a java.net socket
final DatagramSocket socket = new DatagramSocket();
System.err.println("Starting to send packets");
final long start = System.currentTimeMillis();
for (int i = 0; i < eventCount; i++) {
int foo = foos.get(i);
DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo));
socket.send(pkt);
}
socket.close();
*/
// Test by sending over an NIO channel
SocketAddress address = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), SyslogClient.PORT);
final DatagramChannel channel = DatagramChannel.open();
final ByteBuffer buffer = ByteBuffer.allocate(SyslogConnection.MAX_PACKET_SIZE);
buffer.clear();
System.err.println("Starting to send packets");
final long start = System.currentTimeMillis();
for (int i = 0; i < eventCount; i++) {
int foo = foos.get(i);
buffer.put(SyslogClient.getPacketPayload(SyslogClient.LOG_USER, null, SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)));
buffer.flip();
channel.send(buffer, address);
buffer.clear();
}
channel.close();
long mid = System.currentTimeMillis();
System.err.println(String.format("Sent %d packets in %d milliseconds", eventCount, mid - start));
m_eventCounter.waitForFinish(120000);
long end = System.currentTimeMillis();
System.err.println(String.format("Events expected: %d, events received: %d", eventCount, m_eventCounter.getCount()));
final long total = (end - start);
final double eventsPerSecond = (eventCount * 1000.0 / total);
System.err.println(String.format("total time: %d, wait time: %d, events per second: %8.4f", total, (end - mid), eventsPerSecond));
listener.interrupt();
listener.join();
}
use of java.nio.channels.DatagramChannel in project java-design-patterns by iluwatar.
the class NioDatagramChannel method read.
/**
* Reads and returns a {@link DatagramPacket} from the underlying channel.
*
* @return the datagram packet read having the sender address.
*/
@Override
public DatagramPacket read(SelectionKey key) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketAddress sender = ((DatagramChannel) key.channel()).receive(buffer);
/*
* It is required to create a DatagramPacket because we need to preserve which socket address
* acts as destination for sending reply packets.
*/
buffer.flip();
DatagramPacket packet = new DatagramPacket(buffer);
packet.setSender(sender);
return packet;
}
use of java.nio.channels.DatagramChannel in project GwellDemo by dxsdyhm.
the class ShakeTask method run.
@Override
public void run() {
//开始扫描了
handler.sendEmptyMessage(ShakeManager.HANDLE_ID_SEARCH_START);
isRun = true;
try {
selector = Selector.open();
channel = DatagramChannel.open();
//设置非堵塞
channel.configureBlocking(false);
server = channel.socket();
server.bind(new InetSocketAddress(port));
channel.register(selector, SelectionKey.OP_READ);
ByteBuffer receiveBuffer = ByteBuffer.allocate(256);
new Thread() {
@Override
public void run() {
try {
int times = 0;
broadcast = new DatagramSocket();
broadcast.setBroadcast(true);
Log.e("leleshaking", "isRun=" + isRun + "--" + "times=" + times);
while (times < SEND_TIMES) {
if (!isRun) {
return;
}
times++;
Log.e("my", "shake thread send broadcast.");
ShakeData data = new ShakeData();
data.setCmd(ShakeData.Cmd.GET_DEVICE_LIST);
DatagramPacket packet = new DatagramPacket(ShakeData.getBytes(data), ShakeData.getBytes(data).length, InetAddress.getByName("255.255.255.255"), port);
broadcast.send(packet);
Thread.sleep(1000);
}
Log.e("my", "shake thread broadcast end.");
} catch (Exception e) {
Log.e("leleshaking", e.toString());
e.printStackTrace();
} finally {
try {
broadcast.close();
} catch (Exception e) {
e.printStackTrace();
}
ShakeManager.getInstance().stopShaking();
}
}
}.start();
while (isRun) {
int n = selector.select(100);
if (n > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
for (SelectionKey key : keys) {
keys.remove(key);
if (key.isReadable()) {
DatagramChannel dc = (DatagramChannel) key.channel();
InetSocketAddress client = (InetSocketAddress) dc.receive(receiveBuffer);
key.interestOps(SelectionKey.OP_READ);
receiveBuffer.flip();
ShakeData data = ShakeData.getShakeData(receiveBuffer);
switch(data.getCmd()) {
case ShakeData.Cmd.RECEIVE_DEVICE_LIST:
if (data.getError_code() == 1) {
Message msg = new Message();
msg.obj = data;
msg.what = ShakeManager.HANDLE_ID_RECEIVE_DEVICE_INFO;
Bundle bundle = new Bundle();
bundle.putString("ip", client.getAddress().getHostAddress() + "");
msg.setData(bundle);
handler.sendMessage(msg);
break;
} else {
}
receiveBuffer.clear();
}
}
}
}
}
Log.e("my", "shake thread end.");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("leleshaking", e.toString());
e.printStackTrace();
} finally {
ShakeManager.getInstance().stopShaking();
if (null != handler) {
handler.sendEmptyMessage(ShakeManager.HANDLE_ID_APDEVICE_END);
}
try {
server.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
channel.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
selector.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Aggregations