我在网上找了下,用了几个,发现都有问题,因此想问下,谁有一个在局域网里,java udp广播 的代码哦,请给一个哦

解决方案 »

  1.   


               DatagramPacket pd = new DatagramPacket(data, data.length,
                        InetAddress.getByName("255.255.255.255"), port);
               DatagramSocket sendSocket = new DatagramSocket();
               sendSocket.setBroadcast(true);
               sendSocket.send(pd);
      

  2.   

    import java.net.*;
    class WriteServer{
     public static int serverPort = 666 ;
     public static int clientPort = 999 ;
     public static int buffer_size = 1024 ;
     public static  DatagramSocket ds ;
     public static byte buffer[] = new byte[buffer_size]; public static void TheServer() throws Exception{
      int pos = 0;
      while(true){
       int c = System.in.read();
       switch(c){
        case -1:
         System.out.println("Server Quits.");
         return;
        case '\r':
         break;
        case '\n':
         ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort));
         pos = 0;
         break;
        default:
         buffer[pos++] = (byte)c;
       }
      }
     }
     public static void TheClient() throws Exception{
      while(true){
       DatagramPacket p = new DatagramPacket (buffer,buffer.length);
       ds.receive(p);
       System.out.println(new String(p.getData(),0,p.getLength()));
      }
     }
     public static void main(String[] args) throws Exception{
      if(args.length == 1){
       ds = new DatagramSocket(serverPort);
       TheServer();
      }else{
       ds = new DatagramSocket(clientPort);
       TheClient();
      }
     }
    } 运行 java WriteServer
    然后 java WriteServer 1