Created
May 29, 2012 14:45
-
-
Save oogali/2828826 to your computer and use it in GitHub Desktop.
java + multicast testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.*; | |
class McastReceiver { | |
final static String DEFAULT_MCAST_GROUP = "224.56.78.90"; | |
final static int DEFAULT_MCAST_PORT = 12345; | |
final static String JOIN_MSG = "hello!"; | |
MulticastSocket m_McastSock; | |
InetAddress m_Addr; | |
int m_Port; | |
public McastReceiver() { | |
this(DEFAULT_MCAST_GROUP, DEFAULT_MCAST_PORT); | |
} | |
public McastReceiver(String mcastGroup) { | |
this(mcastGroup, DEFAULT_MCAST_PORT); | |
} | |
public McastReceiver(int port) { | |
this(DEFAULT_MCAST_GROUP, port); | |
} | |
public McastReceiver(String mcastGroup, int port) { | |
try { | |
m_Addr = InetAddress.getByName(mcastGroup); | |
m_Port = port; | |
m_McastSock = new MulticastSocket(m_Port); | |
m_McastSock.joinGroup(m_Addr); | |
} catch (Exception e) { | |
System.err.format("Could not create multicast socket: %s\n", e.getMessage()); | |
e.printStackTrace(); | |
} | |
send(JOIN_MSG); | |
} | |
public void send(String msg) { | |
try { | |
DatagramPacket pkt = new DatagramPacket(msg.getBytes(), msg.length(), m_Addr, m_Port); | |
m_McastSock.send(pkt); | |
pkt = null; | |
} catch (Exception e) { | |
System.err.format("Could not construct and send packet: %s\n", e.getMessage()); | |
e.printStackTrace(); | |
} | |
} | |
public static void main(String[] argv) throws InterruptedException { | |
McastReceiver m = new McastReceiver(); | |
while(true) { | |
m.send("what's up?"); | |
Thread.sleep(3000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment