diff options
author | Kjetil Ørbekk <kjetil.orbekk@gmail.com> | 2012-01-10 15:34:55 +0100 |
---|---|---|
committer | Kjetil Ørbekk <kjetil.orbekk@gmail.com> | 2012-01-10 15:34:55 +0100 |
commit | 9a554911174e096b95e99527eac04627400c41ba (patch) | |
tree | 2d36439a69ded1ca54051e3a1636106423c3d7c9 /jsonrpc/src/main/java/com/orbekk/net/BroadcastListener.java |
Initial import of maven projects.
jsonrpc - Common classes.
rpctest - A small xmlrpc project.
master - Android application containing broadcast code and ping service.
Diffstat (limited to 'jsonrpc/src/main/java/com/orbekk/net/BroadcastListener.java')
-rw-r--r-- | jsonrpc/src/main/java/com/orbekk/net/BroadcastListener.java | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/jsonrpc/src/main/java/com/orbekk/net/BroadcastListener.java b/jsonrpc/src/main/java/com/orbekk/net/BroadcastListener.java new file mode 100644 index 0000000..50cdbc7 --- /dev/null +++ b/jsonrpc/src/main/java/com/orbekk/net/BroadcastListener.java @@ -0,0 +1,49 @@ +package com.orbekk.net; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.SocketException; + +import org.apache.log4j.Logger; + +public class BroadcastListener { + private int port; + private Logger logger = Logger.getLogger(getClass()); + + public BroadcastListener(int port) { + this.port = port; + } + + public boolean listen() { + logger.info("Waiting for broadcast on port " + port); + DatagramSocket socket; + try { + socket = new DatagramSocket(port); + } catch (SocketException e) { + logger.warn("Failed to create socket.", e.fillInStackTrace()); + return true; + } + try { + socket.setBroadcast(true); + } catch (SocketException e) { + logger.warn(e.fillInStackTrace()); + } + byte[] buffer = new byte[2048]; + DatagramPacket packet = new DatagramPacket(buffer, buffer.length); + try { + socket.receive(packet); + } catch (IOException e) { + logger.warn(e.fillInStackTrace()); + } + logger.info("Received broadcast from " + packet.getAddress() + + ": " + new String(packet.getData())); + return true; + } + + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + BroadcastListener listener = new BroadcastListener(port); + System.out.println("Received broadcast: " + listener.listen()); + } +} |