下面列出了java.nio.channels.DatagramChannel#connect() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public AsyncDatagramSocket connectDatagram(final SocketAddress remote) throws IOException {
final AsyncDatagramSocket handler = new AsyncDatagramSocket();
final DatagramChannel socket = DatagramChannel.open();
handler.attach(socket);
// ugh.. this should really be post to make it nonblocking...
// but i want datagrams to be immediately writable.
// they're not really used anyways.
Runnable runnable = () -> {
try {
handleSocket(handler);
socket.connect(remote);
}
catch (IOException e) {
StreamUtility.closeQuietly(socket);
}
};
if (getAffinity() != Thread.currentThread()) {
run(runnable);
return handler;
}
runnable.run();
return handler;
}
public void testProcessCommand() throws IOException {
System.out.println("processCommand");
String toString = "test\ntest\nerr\n";
final DatagramChannel channel = DatagramChannelEmul.open();
channel.configureBlocking(false);
final InetSocketAddress inetSocketAddress = new InetSocketAddress(
"localhost", 4444);
channel.connect(inetSocketAddress);
PerfMonMetricGetter instance = new PerfMonMetricGetter(
SigarProxyCache.newInstance(new Sigar(), 500),
new PerfMonWorker(), channel, inetSocketAddress);
instance.addCommandString(toString);
instance.processNextCommand();
instance.processNextCommand();
try {
instance.processNextCommand();
fail();
} catch (UnsupportedOperationException e) {
}
}
public void testReadWrite_NonBlock_WriterNotBound() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
DatagramChannel dc = DatagramChannel.open();
// The writer isn't bound, but is connected.
dc.connect(channel1Address);
dc.configureBlocking(false);
channel2.configureBlocking(false);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));
// Connect channel2 after data has been written.
channel2.connect(dc.socket().getLocalSocketAddress());
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
assertEquals(0, this.channel2.read(targetBuf));
dc.close();
}
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;
}
}
@Test
public void test() throws Exception {
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(true);
channel.connect(new InetSocketAddress(HOSTNAME_BIND, PORT_CRUSHER));
try {
ByteBuffer bb = ByteBuffer.allocate(1024);
bb.limit(800);
bb.position(0);
channel.write(bb);
Thread.sleep(1002);
} finally {
NioUtils.close(channel);
}
}
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
SocketAddress remote = new InetSocketAddress(lh, 1234);
DatagramSocket ds = null;
DatagramChannel dc = null;
try {
ds = new DatagramSocket();
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
check(ds, dc);
ds.connect(remote);
dc.connect(remote);
check(ds, dc);
ds.disconnect();
dc.disconnect();
check(ds, dc);
// repeat tests using socket adapter
ds.connect(remote);
dc.socket().connect(remote);
check(ds, dc);
ds.disconnect();
dc.socket().disconnect();
check(ds, dc);
} finally {
if (ds != null) ds.close();
if (dc != null) dc.close();
}
}
public void testProcessCommand_udp_transmitter() throws IOException {
System.out.println("UDP transmitter");
String cmd = "udp-transmitter:localhost:3333:cpu\tmemory\ttcp\n";
final DatagramChannel channel = DatagramChannelEmul.open();
channel.configureBlocking(false);
final InetSocketAddress inetSocketAddress = new InetSocketAddress(
"localhost", 4444);
channel.connect(inetSocketAddress);
PerfMonMetricGetter instance = new PerfMonMetricGetter(
SigarProxyCache.newInstance(new Sigar(), 500),
new PerfMonWorker(), channel, inetSocketAddress);
instance.addCommandString(cmd);
instance.processNextCommand();
}
private DatagramChannel createChannel(String host, int port, int timeout, int sendBufferSize) {
DatagramChannel datagramChannel = null;
DatagramSocket socket = null;
try {
datagramChannel = DatagramChannel.open();
socket = datagramChannel.socket();
socket.setSoTimeout(timeout);
socket.setSendBufferSize(sendBufferSize);
if (logger.isWarnEnabled()) {
final int checkSendBufferSize = socket.getSendBufferSize();
if (sendBufferSize != checkSendBufferSize) {
logger.warn("DatagramChannel.setSendBufferSize() error. {}!={}", sendBufferSize, checkSendBufferSize);
}
}
InetSocketAddress serverAddress = new InetSocketAddress(host, port);
datagramChannel.connect(serverAddress);
return datagramChannel;
} catch (IOException e) {
IOUtils.closeQuietly(socket);
IOUtils.closeQuietly(datagramChannel);
throw new IllegalStateException("DatagramChannel create fail. Cause" + e.getMessage(), e);
}
}
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
SocketAddress remote = new InetSocketAddress(lh, 1234);
DatagramSocket ds = null;
DatagramChannel dc = null;
try {
ds = new DatagramSocket();
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
check(ds, dc);
ds.connect(remote);
dc.connect(remote);
check(ds, dc);
ds.disconnect();
dc.disconnect();
check(ds, dc);
// repeat tests using socket adapter
ds.connect(remote);
dc.socket().connect(remote);
check(ds, dc);
ds.disconnect();
dc.socket().disconnect();
check(ds, dc);
} finally {
if (ds != null) ds.close();
if (dc != null) dc.close();
}
}
public static void init(final DatagramChannel channel, final InetSocketAddress sendAddress)
throws IOException
{
channel.configureBlocking(false);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.connect(sendAddress);
}
private DatagramChannel createChannel() throws IOException {
logi(TAG, "Open");
DatagramChannel datagramChannel = DatagramChannel.open();
datagramChannel.configureBlocking(false);
datagramChannel.connect(getRewrittenDestination());
return datagramChannel;
}
static DatagramChannel openServerChannel(DatagramChannel clientChannel) throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, loopbackInterface());
channel.connect(new InetSocketAddress(multicastGroup(), getLocalPort(clientChannel)));
return channel;
}
public void test_write_LBuffer_positioned() throws Exception {
// Regression test for Harmony-683
int position = 16;
DatagramChannel dc = DatagramChannel.open();
byte[] sourceArray = new byte[CAPACITY_NORMAL];
dc.connect(datagramSocket1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
sourceBuf.position(position);
assertEquals(CAPACITY_NORMAL - position, dc.write(sourceBuf));
}
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
SocketAddress remote = new InetSocketAddress(lh, 1234);
DatagramSocket ds = null;
DatagramChannel dc = null;
try {
ds = new DatagramSocket();
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
check(ds, dc);
ds.connect(remote);
dc.connect(remote);
check(ds, dc);
ds.disconnect();
dc.disconnect();
check(ds, dc);
// repeat tests using socket adapter
ds.connect(remote);
dc.socket().connect(remote);
check(ds, dc);
ds.disconnect();
dc.socket().disconnect();
check(ds, dc);
} finally {
if (ds != null) ds.close();
if (dc != null) dc.close();
}
}
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
SocketAddress remote = new InetSocketAddress(lh, 1234);
DatagramSocket ds = null;
DatagramChannel dc = null;
try {
ds = new DatagramSocket();
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
check(ds, dc);
ds.connect(remote);
dc.connect(remote);
check(ds, dc);
ds.disconnect();
dc.disconnect();
check(ds, dc);
// repeat tests using socket adapter
ds.connect(remote);
dc.socket().connect(remote);
check(ds, dc);
ds.disconnect();
dc.socket().disconnect();
check(ds, dc);
} finally {
if (ds != null) ds.close();
if (dc != null) dc.close();
}
}
/**
* Test method for 'DatagramChannelImpl.socket()'
*/
public void testSocket_Block_BasicStatusAfterConnect() throws IOException {
final DatagramChannel dc = DatagramChannel.open();
dc.connect(datagramSocket1Address);
DatagramSocket s1 = dc.socket();
assertSocketAfterConnect(s1);
DatagramSocket s2 = dc.socket();
// same
assertSame(s1, s2);
dc.close();
}
@SuppressWarnings("resource")
public static @Nullable SelectionKey openUnicastChannel(@Nullable Selector selector, String logId,
@Nullable InetSocketAddress address) throws IOException {
if (selector == null || address == null) {
return null;
}
DatagramChannel unicastChannel = DatagramChannel.open(StandardProtocolFamily.INET)
.setOption(StandardSocketOptions.SO_REUSEADDR, true);
unicastChannel.configureBlocking(false);
unicastChannel.connect(address);
LOGGER.trace("{} : Connected to light via {}", logId, unicastChannel.getLocalAddress().toString());
return unicastChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public static void main(String[] args) throws Exception {
InetAddress lh = InetAddress.getLocalHost();
SocketAddress remote = new InetSocketAddress(lh, 1234);
DatagramSocket ds = null;
DatagramChannel dc = null;
try {
ds = new DatagramSocket();
dc = DatagramChannel.open().bind(new InetSocketAddress(0));
check(ds, dc);
ds.connect(remote);
dc.connect(remote);
check(ds, dc);
ds.disconnect();
dc.disconnect();
check(ds, dc);
// repeat tests using socket adapter
ds.connect(remote);
dc.socket().connect(remote);
check(ds, dc);
ds.disconnect();
dc.socket().disconnect();
check(ds, dc);
} finally {
if (ds != null) ds.close();
if (dc != null) dc.close();
}
}
static MarketData open(String session, NetworkInterface multicastInterface,
InetSocketAddress multicastGroup,
InetSocketAddress requestAddress) throws IOException {
DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, multicastInterface);
channel.connect(multicastGroup);
MoldUDP64Server transport = new MoldUDP64Server(channel, session);
DatagramChannel requestChannel = DatagramChannel.open();
requestChannel.bind(requestAddress);
requestChannel.configureBlocking(false);
MoldUDP64RequestServer requestTransport = new MoldUDP64RequestServer(requestChannel);
return new MarketData(transport, requestTransport);
}
/**
* 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);
}