4
|
1 package wifibroadcast;
|
|
2
|
|
3 import java.io.IOException;
|
|
4 import java.net.DatagramPacket;
|
|
5 import java.net.DatagramSocket;
|
|
6 import java.net.InetAddress;
|
|
7 import java.net.InetSocketAddress;
|
|
8 import java.net.SocketException;
|
|
9 import java.net.UnknownHostException;
|
|
10 import java.nio.ByteBuffer;
|
|
11
|
|
12 public class WifiDatagram implements WifiReceiver {
|
19
|
13 /**
|
|
14 * Test class for non broadcast/multicast datagram
|
|
15 */
|
4
|
16
|
|
17 private DatagramSocket s;
|
|
18 private int port;
|
|
19 private InetAddress mAddr;
|
|
20
|
9
|
21 public WifiDatagram(int id, int port, SocketType sender) throws IOException {
|
4
|
22 this.port = port;
|
|
23
|
|
24 if (sender == SocketType.Sender) {
|
|
25 try {
|
|
26 InetAddress address0 = getLocalAddress();
|
|
27 System.out.println("Found broadcast "+address0);
|
|
28 mAddr = address0;
|
|
29 s = new DatagramSocket();
|
|
30 s.bind(new InetSocketAddress(address0,port+1));
|
|
31 s.setBroadcast(true);
|
|
32 } catch (SocketException e) {
|
|
33 }
|
|
34 } else {
|
|
35 // InetAddress address0 = getBroadcast();
|
|
36 s = new DatagramSocket(port);
|
|
37 // s.bind(new InetSocketAddress(address0,port));
|
|
38 s.setReuseAddress(true);
|
|
39 s.setBroadcast(true);
|
|
40 }
|
|
41 }
|
|
42
|
|
43 public void recieve(ByteBuffer testData, long timeout) throws IOException {
|
|
44 DatagramPacket packet = new DatagramPacket(testData.array(),testData.capacity());
|
|
45 s.receive(packet);
|
|
46 testData.limit(packet.getLength());
|
|
47 testData.position(0);
|
|
48 return; // one at a time
|
|
49 }
|
|
50
|
|
51
|
|
52 public void send(ByteBuffer testData) throws IOException {
|
|
53 DatagramPacket sendPacket = new DatagramPacket(testData.array(), testData.limit(),mAddr, port);
|
|
54 s.send(sendPacket);
|
|
55 testData.position(testData.limit());
|
|
56 System.out.println("send");
|
|
57 }
|
|
58
|
|
59 public InetAddress getLocalAddress() throws UnknownHostException {
|
|
60 return InetAddress.getByName("127.0.0.1");
|
|
61 }
|
|
62
|
19
|
63 @Override
|
|
64 public void selectMode(boolean mode) {
|
|
65 }
|
|
66
|
4
|
67 }
|