changeset 11:7912fd3af027

non select mode on DatagramChannel.
author one
date Sun, 29 Jul 2012 12:10:17 +0900
parents fc180f38257e
children e1f43b669cdb
files src/wifibroadcast/WifiMulticastChannel.java
diffstat 1 files changed, 24 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/src/wifibroadcast/WifiMulticastChannel.java	Sun Jul 29 11:10:08 2012 +0900
+++ b/src/wifibroadcast/WifiMulticastChannel.java	Sun Jul 29 12:10:17 2012 +0900
@@ -17,7 +17,9 @@
 	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
@@ -36,28 +38,42 @@
 
 		dc = DatagramChannel.open(StandardProtocolFamily.INET)
 				.setOption(StandardSocketOptions.SO_REUSEADDR, true)
-				.bind(sAddr = new InetSocketAddress(port))
 				.setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);
 
 		mAddr = InetAddress.getByName(mCASTADDR);
-
+		sAddr = new InetSocketAddress(mAddr,port);
 		dc.join(mAddr, ni);
-		dc.configureBlocking(false);
-		dc.register(selector, SelectionKey.OP_READ);
+		
+		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 (selector.select(timeout)>0) {
-			dc.receive(testData);
-		} else {
+		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 {
-		dc.send(testData, sAddr);
+		while(testData.hasRemaining()) {
+			dc.send(testData, sAddr);
+		}
+		try {
+			Thread.sleep(100);
+		} catch (InterruptedException e) {
+		}
 	}
 
 }