view src/wifibroadcast/WifiBroadcast.java @ 2:2a328333ba70

no compile errors
author one
date Sat, 28 Jul 2012 13:06:57 +0900
parents 649b8573372c
children 9c99e2193277
line wrap: on
line source

package wifibroadcast;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
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;
import java.util.Iterator;

public class WifiBroadcast implements WifiReceiver {

	private DatagramChannel channel;
	private Selector selector;

	public WifiBroadcast(int port) throws IOException {
		selector = SelectorProvider.provider().openSelector();		
		channel = SelectorProvider.provider().openDatagramChannel();
		channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
		channel.configureBlocking(false);
		try {
			InetSocketAddress address = new InetSocketAddress("::", port);
			channel.connect(address);
		} catch (SocketException e) {
			// for some bad IPv6 implementation
			channel.connect(new InetSocketAddress(port));
		}
		channel.register(selector, SelectionKey.OP_READ);
	}

	public void recieve(ByteBuffer testData, long timeout) throws IOException {
		if (selector.select(timeout)>0) {
			for (Iterator<SelectionKey> it = selector.selectedKeys().iterator();it.hasNext(); ) {
				SelectionKey s = it.next();
				it.remove();
				DatagramChannel ch = (DatagramChannel)s.channel();
				ch.read(testData);
				testData.flip();
				return; // one at a time
			}
		}
	}


	public void send(ByteBuffer testData) throws IOException {
		channel.write(testData);
	}
}