Mercurial > hg > Members > kono > WifiBroadcast
comparison src/wifibroadcast/WifiBroadcast.java @ 1:649b8573372c
cleanup
author | one |
---|---|
date | Sat, 28 Jul 2012 12:24:04 +0900 |
parents | src/wifibroadcast/WifiBroadcastReciver.java@df9d16620c08 |
children | 2a328333ba70 |
comparison
equal
deleted
inserted
replaced
0:df9d16620c08 | 1:649b8573372c |
---|---|
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.DatagramChannel; | |
9 import java.nio.channels.SelectionKey; | |
10 import java.nio.channels.Selector; | |
11 import java.nio.channels.spi.SelectorProvider; | |
12 import java.util.Iterator; | |
13 | |
14 public class WifiBroadcast implements WifiReceiver,WifiSender { | |
15 | |
16 private DatagramChannel channel; | |
17 private Selector selector; | |
18 | |
19 public WifiBroadcast(int port) throws IOException { | |
20 selector = SelectorProvider.provider().openSelector(); | |
21 channel = SelectorProvider.provider().openDatagramChannel(); | |
22 channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); | |
23 try { | |
24 InetSocketAddress address = new InetSocketAddress("::", port); | |
25 channel.socket().bind(address); | |
26 } catch (SocketException e) { | |
27 // for some bad IPv6 implementation | |
28 channel.socket().bind(new InetSocketAddress(port)); | |
29 } | |
30 channel.register(selector, SelectionKey.OP_READ); | |
31 } | |
32 | |
33 public void recieve(ByteBuffer testData, long timeout) throws IOException { | |
34 if (selector.select(timeout)>0) { | |
35 for (Iterator<SelectionKey> it = selector.selectedKeys().iterator();it.hasNext(); ) { | |
36 SelectionKey s = it.next(); | |
37 it.remove(); | |
38 DatagramChannel ch = (DatagramChannel)s.channel(); | |
39 ch.read(testData); | |
40 testData.flip(); | |
41 return; // one at a time | |
42 } | |
43 } | |
44 } | |
45 | |
46 | |
47 public void send(ByteBuffer testData) throws IOException { | |
48 channel.write(testData); | |
49 } | |
50 } |