日期:2014-05-20 浏览次数:20894 次
package UdpDemo; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class UdpDemo { /** * @param args */ public static void main(String[] args) { try { DatagramSocket ds=new DatagramSocket(); byte[] buf="this is demo".getBytes(); try { DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10000); try { System.out.println("开始发送...."); ds.send(dp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }System.out.println("关闭资源"); ds.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package UdpDemo; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UpRece{ public static void main(String[] args) throws Exception{ // 创建端点 DatagramSocket ds=new DatagramSocket(10000); //定义数据包 存储数据 byte[] buffer=new byte[1024]; DatagramPacket dp=new DatagramPacket(buffer, buffer.length); System.out.println("开始接收"); ds.receive(dp); System.out.println("开始分类获取"); String ip=dp.getAddress().getHostAddress(); String Data=new String(dp.getData(),0, dp.getLength()); int port=dp.getPort(); System.out.println(ip+":"+Data+"::"+port); ds.close(); } }