Mercurial > hg > Members > kono > WifiBroadcast
view src/wifibroadcast/WifiMulticastChannel.java @ 11:7912fd3af027
non select mode on DatagramChannel.
author | one |
---|---|
date | Sun, 29 Jul 2012 12:10:17 +0900 |
parents | 95d58cc5bb0b |
children | e1f43b669cdb |
line wrap: on
line source
package wifibroadcast; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketAddress; import java.net.StandardProtocolFamily; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; public class WifiMulticastChannel implements WifiReceiver { private InetAddress mAddr; private DatagramChannel dc; private SocketAddress sAddr; // select on DatagramChannel does not work now private Selector selector; private boolean selectMode = false; public WifiMulticastChannel(int id, String mCASTADDR, int port, SocketType sender) throws IOException { // join multicast group on this interface, and also use this // interface for outgoing multicast datagrams selector = SelectorProvider.provider().openSelector(); NetworkInterface ni = NetworkInterface.getByName("en1"); if (ni==null) { System.err.println("Can't open network interface "+"en1"); throw new IOException(); } if (!ni.supportsMulticast()) { System.err.println("Network interface does not support multicast"+"en1"); throw new IOException(); } dc = DatagramChannel.open(StandardProtocolFamily.INET) .setOption(StandardSocketOptions.SO_REUSEADDR, true) .setOption(StandardSocketOptions.IP_MULTICAST_IF, ni); mAddr = InetAddress.getByName(mCASTADDR); sAddr = new InetSocketAddress(mAddr,port); dc.join(mAddr, ni); if (sender == SocketType.Receiver) { dc.bind(new InetSocketAddress(port)); if (selectMode) { dc.configureBlocking(false); dc.register(selector, SelectionKey.OP_READ); } } } @Override public void recieve(ByteBuffer testData, long timeout) throws IOException { if (selectMode && selector.select(timeout)==0) { System.out.println("bad select "+timeout); testData.limit(0); testData.position(0); return; } SocketAddress s = dc.receive(testData); testData.flip(); System.out.println("From "+s+" "+testData.remaining()+" bytes."); } @Override public void send(ByteBuffer testData) throws IOException { while(testData.hasRemaining()) { dc.send(testData, sAddr); } try { Thread.sleep(100); } catch (InterruptedException e) { } } }