本文整理匯總了Java中java.nio.channels.DatagramChannel類的典型用法代碼示例。如果您正苦於以下問題:Java DatagramChannel類的具體用法?Java DatagramChannel怎麽用?Java DatagramChannel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
DatagramChannel類屬於java.nio.channels包,在下文中一共展示了DatagramChannel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: main
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
public static void main(String[] args) throws IOException
{
ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
DatagramChannel dgChannel = DatagramChannel.open();
for(int i = 0; i < targets.length; i++){
data.rewind();
SocketAddress sa = new InetSocketAddress(targets[i], port);
System.out.println("-------------\nDG_Sending data:" +
"\n remaining:" + data.remaining() +
"\n position:" + data.position() +
"\n limit:" + data.limit() +
"\n capacity:" + data.capacity() +
" bytes on DG channel to " + sa);
try {
int n = dgChannel.send(data, sa);
System.out.println("DG_Sent " + n + " bytes");
} catch (IOException e) {
//This regression test is to check vm crash only, so ioe is OK.
e.printStackTrace();
}
}
dgChannel.close();
}
示例2: JdpBroadcaster
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
示例3: newHandle
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
@Override
protected DatagramChannel newHandle(SocketAddress localAddress) throws Exception {
DatagramChannel ch = DatagramChannel.open();
try {
if (localAddress != null) {
ch.socket().bind(localAddress);
}
return ch;
} catch (Exception e) {
// If we got an exception while binding the datagram,
// we have to close it otherwise we will loose an handle
ch.close();
throw e;
}
}
示例4: run
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
public void run () {
if (mIsConnected) return;
try {
mChannel = DatagramChannel.open();
mChannel.configureBlocking(false);
mChannel.connect(new InetSocketAddress(mAddress, mPort));
if (mListenerThread == null) {
mListenerThread = new ListenerThread();
mListenerThread.start();
mActivityHandler.sendMessage(composeMessage(MSG_ON_CONNECT, ""));
mIsConnected = true;
}
Looper.prepare();
mSendHandler = new Handler();
Looper.loop();
} catch (Exception e) {
mActivityHandler.sendMessage(composeMessage(MSG_ON_CONNECTION_FAIL, e.toString()));
}
}
示例5: checkSocket
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
/**
* resolves host, builds socket, returns true if it succeeds
*/
private boolean checkSocket() {
if ((channel != null) && channel.isOpen()) { //if(datagramSocket!=null && datagramSocket.isBound()) {
return true;
}
try {
channel = DatagramChannel.open();
datagramSocket = channel.socket();
datagramSocket.setReuseAddress(true);
// disable timeout so that receive just waits for data forever (until interrupted)
// datagramSocket.setSoTimeout(TIMEOUT_MS);
// if (datagramSocket.getSoTimeout() != TIMEOUT_MS) {
// log.warning("datagram socket read timeout value read=" + datagramSocket.getSoTimeout() + " which is different than timeout value of " + TIMEOUT_MS + " that we tried to set - perhaps timeout is not supported?");
// }
SocketAddress address = new InetSocketAddress(getPort());
datagramSocket.bind(address);
log.info("bound " + this);
datagramSocket.setSoTimeout(0); // infinite timeout
return true;
} catch (IOException e) {
log.warning("caught " + e + ", datagramSocket will be constructed later");
return false;
}
}
示例6: run
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
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;
}
}
示例7: launchWithDatagramChannel
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
public static DatagramChannel launchWithDatagramChannel(String className, String options[], String args[])
throws IOException
{
DatagramChannel dc = DatagramChannel.open();
dc.socket().bind(new InetSocketAddress(0));
int port = dc.socket().getLocalPort();
launch(className, options, args, Util.getFD(dc));
dc.close();
dc = DatagramChannel.open();
InetAddress address = InetAddress.getLocalHost();
if (address.isLoopbackAddress()) {
address = InetAddress.getLoopbackAddress();
}
InetSocketAddress isa = new InetSocketAddress(address, port);
dc.connect(isa);
return dc;
}
示例8: UDPEchoTest
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
private static void UDPEchoTest() throws IOException {
DatagramChannel dc = Launcher.launchWithDatagramChannel(ECHO_SERVICE, null);
String msg = "I was out saving the galaxy when your grandfather was in diapers";
ByteBuffer bb = ByteBuffer.wrap(msg.getBytes("UTF-8"));
dc.write(bb);
// and receive the echo
byte b[] = new byte[msg.length() + 100];
DatagramPacket pkt2 = new DatagramPacket(b, b.length);
dc.socket().setSoTimeout(5000);
dc.socket().receive(pkt2);
if (pkt2.getLength() != msg.length()) {
throw new RuntimeException("Received packet of incorrect length");
}
dc.close();
}
示例9: start
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
public synchronized void start() throws IOException {
if (running) {
return;
}
// Start channel
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(true);
channel.socket().bind(new InetSocketAddress(port));
running = true;
// Start server thread
new ServerThread(channel).start();
log.info("DNS server started");
}
示例10: open
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
@Override
protected DatagramChannel open(SocketAddress localAddress) throws Exception {
final DatagramChannel c = DatagramChannel.open();
boolean success = false;
try {
new NioDatagramSessionConfig(c).setAll(getSessionConfig());
c.configureBlocking(false);
c.socket().bind(localAddress);
c.register(selector, SelectionKey.OP_READ);
success = true;
} finally {
if (!success) {
close(c);
}
}
return c;
}
示例11: isReadable
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
@Override
protected boolean isReadable(DatagramChannel handle) {
SelectionKey key = handle.keyFor(selector);
if ((key == null) || (!key.isValid())) {
return false;
}
return key.isReadable();
}
示例12: isWritable
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
@Override
protected boolean isWritable(DatagramChannel handle) {
SelectionKey key = handle.keyFor(selector);
if ((key == null) || (!key.isValid())) {
return false;
}
return key.isWritable();
}
示例13: localAddress
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
@Override
protected SocketAddress localAddress(DatagramChannel handle) throws Exception {
InetSocketAddress inetSocketAddress = (InetSocketAddress) handle.socket().getLocalSocketAddress();
InetAddress inetAddress = inetSocketAddress.getAddress();
if ((inetAddress instanceof Inet6Address) && (((Inet6Address) inetAddress).isIPv4CompatibleAddress())) {
// Ugly hack to workaround a problem on linux : the ANY address is always converted to IPV6
// even if the original address was an IPV4 address. We do store the two IPV4 and IPV6
// ANY address in the map.
byte[] ipV6Address = ((Inet6Address) inetAddress).getAddress();
byte[] ipV4Address = new byte[4];
for (int i = 0; i < 4; i++) {
ipV4Address[i] = ipV6Address[12 + i];
}
InetAddress inet4Adress = Inet4Address.getByAddress(ipV4Address);
return new InetSocketAddress(inet4Adress, inetSocketAddress.getPort());
} else {
return inetSocketAddress;
}
}
示例14: close
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
@Override
protected void close(DatagramChannel handle) throws Exception {
SelectionKey key = handle.keyFor(selector);
if (key != null) {
key.cancel();
}
handle.disconnect();
handle.close();
}
示例15: sendAck
import java.nio.channels.DatagramChannel; //導入依賴的package包/類
/**
* send a reply-acknowledgement (6,2,3), sends it doing a busy write, the ACK is so small
* that it should always go to the buffer
* @param key
* @param channel
*/
protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) {
try {
ByteBuffer buf = ByteBuffer.wrap(command);
int total = 0;
if (channel instanceof DatagramChannel) {
DatagramChannel dchannel = (DatagramChannel)channel;
//were using a shared channel, document says its thread safe
//TODO check optimization, one channel per thread?
while ( total < command.length ) {
total += dchannel.send(buf, udpaddr);
}
} else {
while ( total < command.length ) {
total += channel.write(buf);
}
}
if (log.isTraceEnabled()) {
log.trace("ACK sent to " +
( (channel instanceof SocketChannel) ?
((SocketChannel)channel).socket().getInetAddress() :
((DatagramChannel)channel).socket().getInetAddress()));
}
} catch ( java.io.IOException x ) {
log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage());
}
}