UDP java实现局域网发和收

来源:互联网 发布:强力安卓数据恢复精灵 编辑:程序博客网 时间:2024/05/21 09:48

 

importjava.io.IOException;

importjava.net.DatagramPacket;

importjava.net.InetAddress;

importjava.net.MulticastSocket;

 

 

publicclassMulticastSenderFirst{

   

    static StringipAddr ="224.0.0.1";

   staticintport = 8888;

   

    privateInetAddressaddress;

 

   public MulticastSenderFirst()throwsIOException{

       address = InetAddress.getByName(ipAddr);

   }

   publicvoid run(){

       intindex=1;

       try(MulticastSocketsocket =newMulticastSocket(port)) {

           while (true){

               String sen="///////////"+(++index);

               byte[]output = (sen).getBytes();

 

               System.out.println("Sent"+output);

               socket.send(newDatagramPacket(output,output.length,address,port));

               Thread.sleep(5000);

           }

       }catch (Exceptionex){

           ex.printStackTrace();

       }

 

   }

   

    publicstaticvoidmain(String[]arg) {

       try {

           new MulticastSenderFirst().run();

       } catch (IOExceptione) {

           e.printStackTrace();

       }

   }

}

 

 

 

importjava.net.DatagramPacket;

importjava.net.InetAddress;

importjava.net.MulticastSocket;

 

publicclassMulticastReceiverFirst {

   static String_ipAddr ="224.0.0.1";

   staticint_port = 8888;

 

   publicstaticvoidmain(String[]args)throws Exception{

       MulticastSocket socket =newMulticastSocket(_port);

       InetAddress address = InetAddress.getByName(_ipAddr);

       socket.joinGroup(address);

 

       byte[]input =newbyte[1024];

       DatagramPacket inPacket =newDatagramPacket(input,input.length);

 

       while (true){

           socket.receive(inPacket);

           String recived=new String(input,0,inPacket.getLength());

           System.out.println("--->--->"+recived);

       }

   }

}

 

 

原创粉丝点击