tuxmartin

MulticastSocketServer

Feb 12th, 2015
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.net.DatagramPacket;
  3. import java.net.DatagramSocket;
  4. import java.net.Inet4Address;
  5. import java.net.Inet6Address;
  6. import java.net.InetAddress;
  7. import java.net.NetworkInterface;
  8. import java.net.SocketException;
  9. import java.net.UnknownHostException;
  10. import java.util.Enumeration;
  11.  
  12. // http://examples.javacodegeeks.com/core-java/net/multicastsocket-net/java-net-multicastsocket-example/
  13. public class MulticastSocketServer {
  14.  
  15.     final static String INET_ADDR = "224.0.0.3";
  16.     final static int PORT = 8888;
  17.  
  18.     public static void main(String[] args) throws UnknownHostException,
  19.             InterruptedException, SocketException {
  20.         // Get the address that we are going to connect to.
  21.         InetAddress addr = InetAddress.getByName(INET_ADDR);
  22.  
  23.         String streamIP = "";
  24.         // http://stackoverflow.com/a/7541175/1974494
  25.         NetworkInterface ni = NetworkInterface.getByName("eth0");
  26.         Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
  27.         while (inetAddresses.hasMoreElements()) {
  28.             InetAddress ia = inetAddresses.nextElement();
  29.             if (!ia.isLinkLocalAddress()) {
  30.                 System.out.println("IP: " + ia.getHostAddress());
  31.                 streamIP = ia.getHostAddress();
  32.             }
  33.         }
  34.  
  35.         int i=0;
  36.         // Open a new DatagramSocket, which will be used to send the data.
  37.         try (DatagramSocket serverSocket = new DatagramSocket()) {
  38.             while (true) {
  39.                 String msg = "udp://" + streamIP + ":1234";
  40.  
  41.                 // Create a packet that will contain the data
  42.                 // (in the form of bytes) and send it.
  43.                 DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
  44.                         msg.getBytes().length, addr, PORT);
  45.                 serverSocket.send(msgPacket);
  46.  
  47.                 System.out.println("Server sent packet " +i+ " with msg: " + msg);
  48.                 i++;
  49.                 Thread.sleep(1000);
  50.             }
  51.         } catch (IOException ex) {
  52.             ex.printStackTrace();
  53.         }
  54.     }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment