标签:style blog io color os sp java on 数据
//127.0.0.1是本机IP地址
package lianxi1; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import org.junit.Test; public class TestUDP1 { @Test public void send(){ DatagramSocket ds = null; try { ds = new DatagramSocket(); String str = "我是UDP数据报"; byte[] b = str.getBytes(); DatagramPacket dp = new DatagramPacket(b, 0, b.length, InetAddress .getByName("127.0.0.1"), 9910); ds.send(dp); } catch (Exception e) { // TODO: handle exception } if(ds!=null){ ds.close(); } } @Test public void receive(){ DatagramSocket ds = null; try { ds = new DatagramSocket(9910); byte[] b = new byte[200]; DatagramPacket dp = new DatagramPacket(b, 0, b.length); ds.receive(dp); String str = new String(dp.getData(),0,dp.getLength()); System.out.println(str); } catch (Exception e) { // TODO: handle exception } if(ds!=null){ ds.close(); } } }
标签:style blog io color os sp java on 数据
原文地址:http://www.cnblogs.com/yjtm53/p/4168015.html