UDP 데이터 전송 및 수신

1788 단어
발송자:
packagecom.kvt.udp;
importjava.io.IOException;
importjava.net.DatagramPacket;
importjava.net.DatagramSocket;
importjava.net.InetAddress;
importjava.net.SocketException;
importjava.net.UnknownHostException;
/**
 * UDP      :UDP            ,           。
 *            ,      ,       。
 *           。
 */
publicclassUdpSend {
    publicstaticvoidmain(String[] args) throwsSocketException, UnknownHostException {
        DatagramSocket ds=newDatagramSocket();
        String str="china";
        DatagramPacket dp=newDatagramPacket(str.getBytes(), str.length(),InetAddress.getByName("192.168.20.48"), 8000);
        try{
            ds.send(dp);
        } catch(IOException e) {
            e.printStackTrace();
        }finally{
            ds.close();
        }
         
    }
 
}

수신자:
packagecom.kvt.udp;
importjava.io.IOException;
importjava.net.DatagramPacket;
importjava.net.DatagramSocket;
importjava.net.SocketException;
importjava.net.UnknownHostException;
/**
 * UDP      :UDP            ,           。
 *            ,      ,       。
 *           。
 */
publicclassUdpReceive {
    publicstaticvoidmain(String[] args) throwsSocketException, UnknownHostException {
        DatagramSocket ds=newDatagramSocket(8000);
        byte[] byt=newbyte[1024];
        DatagramPacket dp=newDatagramPacket(byt,byt.length);
        try{
            ds.receive(dp);
            String str=newString(dp.getData(),0,dp.getLength());
            System.out.println(str);
            System.out.println("IP:"+dp.getAddress().getHostAddress()+" Port:"+dp.getPort());
        } catch(IOException e) {
            e.printStackTrace();
        }finally{
            ds.close();
        }
         
         
    }
 
}

좋은 웹페이지 즐겨찾기