Mercurial > hg > Members > kono > WifiBroadcast
comparison src/wifibroadcast/WifiBroadcastReciver.java @ 0:df9d16620c08
Wifi broad cast test program
author | Shinji KONO <kono@ie.u-ryukyu.ac.jp> |
---|---|
date | Sat, 28 Jul 2012 12:16:49 +0900 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:df9d16620c08 |
---|---|
1 package wifibroadcast; | |
2 | |
3 import java.io.IOException; | |
4 import java.net.InetSocketAddress; | |
5 import java.net.SocketException; | |
6 import java.net.StandardSocketOptions; | |
7 import java.nio.ByteBuffer; | |
8 import java.nio.channels.ClosedChannelException; | |
9 import java.nio.channels.DatagramChannel; | |
10 import java.nio.channels.SelectionKey; | |
11 import java.nio.channels.Selector; | |
12 import java.nio.channels.spi.SelectorProvider; | |
13 import java.util.Iterator; | |
14 | |
15 import fdl.TupleHandler; | |
16 | |
17 public class WifiBroadcastReciver implements WifiReciver { | |
18 | |
19 private DatagramChannel channel; | |
20 private Selector selector; | |
21 | |
22 public WifiBroadcastReciver(int port) throws IOException { | |
23 selector = SelectorProvider.provider().openSelector(); | |
24 channel = SelectorProvider.provider().openDatagramChannel(); | |
25 channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); | |
26 try { | |
27 InetSocketAddress address = new InetSocketAddress("::", port); | |
28 channel.socket().bind(address); | |
29 } catch (SocketException e) { | |
30 // for some bad IPv6 implementation | |
31 channel.socket().bind(new InetSocketAddress(port)); | |
32 } | |
33 channel.register(selector, SelectionKey.OP_READ); | |
34 } | |
35 | |
36 public void recieve(ByteBuffer testData, long timeout) throws IOException { | |
37 if (selector.select(timeout)>0) { | |
38 for (Iterator<SelectionKey> it = selector.selectedKeys().iterator();it.hasNext(); ) { | |
39 SelectionKey s = it.next(); | |
40 it.remove(); | |
41 DatagramChannel ch = (DatagramChannel)s.channel(); | |
42 ch.read(testData); | |
43 testData.flip(); | |
44 return; // one at a time | |
45 } | |
46 } | |
47 } | |
48 | |
49 } |