Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.Inet4Address;
- import java.net.Inet6Address;
- import java.net.InetAddress;
- import java.net.NetworkInterface;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- import java.util.Enumeration;
- // http://examples.javacodegeeks.com/core-java/net/multicastsocket-net/java-net-multicastsocket-example/
- public class MulticastSocketServer {
- final static String INET_ADDR = "224.0.0.3";
- final static int PORT = 8888;
- public static void main(String[] args) throws UnknownHostException,
- InterruptedException, SocketException {
- // Get the address that we are going to connect to.
- InetAddress addr = InetAddress.getByName(INET_ADDR);
- String streamIP = "";
- // http://stackoverflow.com/a/7541175/1974494
- NetworkInterface ni = NetworkInterface.getByName("eth0");
- Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
- while (inetAddresses.hasMoreElements()) {
- InetAddress ia = inetAddresses.nextElement();
- if (!ia.isLinkLocalAddress()) {
- System.out.println("IP: " + ia.getHostAddress());
- streamIP = ia.getHostAddress();
- }
- }
- int i=0;
- // Open a new DatagramSocket, which will be used to send the data.
- try (DatagramSocket serverSocket = new DatagramSocket()) {
- while (true) {
- String msg = "udp://" + streamIP + ":1234";
- // Create a packet that will contain the data
- // (in the form of bytes) and send it.
- DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
- msg.getBytes().length, addr, PORT);
- serverSocket.send(msgPacket);
- System.out.println("Server sent packet " +i+ " with msg: " + msg);
- i++;
- Thread.sleep(1000);
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment