本文整理匯總了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();
}
}