首页 > 代码库 > UDP/IP协议的网络编程

UDP/IP协议的网络编程

//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();    }}        }

UDP/IP协议的网络编程