本文整理汇总了Java中java.nio.channels.DatagramChannel.bind方法的典型用法代码示例。如果您正苦于以下问题:Java DatagramChannel.bind方法的具体用法?Java DatagramChannel.bind怎么用?Java DatagramChannel.bind使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.nio.channels.DatagramChannel
的用法示例。
在下文中一共展示了DatagramChannel.bind方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createDatagramChannel
import java.nio.channels.DatagramChannel; //导入方法依赖的package包/类
/**
*
* @param port
* @param addr
* @return
* @throws Exception
*/
public static DatagramChannel createDatagramChannel(int port, InetAddress addr) throws Exception {
final DatagramChannel channel = DatagramChannel.open();
if (addr == null) {
channel.bind(new InetSocketAddress(port));
}
else {
channel.bind(new InetSocketAddress(addr, port));
}
return channel;
}
示例2: test
import java.nio.channels.DatagramChannel; //导入方法依赖的package包/类
private static void test() throws Exception {
DatagramChannel dc = DatagramChannel.open();
InetAddress localHost = InetAddress.getLocalHost();
dc.bind(new InetSocketAddress(localHost, 0));
Server server = new Server(dc.getLocalAddress());
Thread serverThread = new Thread(server);
serverThread.start();
try {
InetSocketAddress isa = new InetSocketAddress(localHost, server.port());
dc.connect(isa);
ByteBuffer bb = ByteBuffer.allocateDirect(12);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putInt(1).putLong(1);
bb.flip();
dc.write(bb);
bb.rewind();
dc.write(bb);
bb.rewind();
dc.write(bb);
Thread.sleep(2000);
serverThread.interrupt();
server.throwException();
} finally {
dc.close();
}
}