客户端发送:
package socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* UDP发送方
* 步骤:
* 1、获取本地主机的InetAddress
* 2、创建DatagramPacket对象,封装要发送的信息
* 3、利用DatagramSocket对象将DatagramSocket对象发送出去
* @author Administrator
*
*/
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDPSend {
public static void main(String[] args) {
//待发送的信息
String msg="你好,我是用UDP给你发送信息的";
try {
//获取本地主机地址
InetAddress ia=InetAddress.getByName("localhost");
//创建DatagramSocket对象,封装数据
DatagramPacket dp=new DatagramPacket(msg.getBytes(), msg.getBytes().length, ia, 8800);
//创建DatagramSocket,想服务器发送数据
DatagramSocket ds=null;
try {
ds = new DatagramSocket();
ds.send(dp);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ds.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务端接收:
package socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* UDP信息接收
* 步骤:
* 1、创建DatagramPacket对象,准备接收封装的数据
* 2、创建DatagramSocket对象,接收数据保存于DatagramPacket对象中
* 3、创建DatagramPacket对象处理数据
* @author Administrator
*
*/
public class UDPReceive {
public static void main(String[] args) {
byte[] buf=new byte[1024];
//创建DatagramPacket对象,准备接收封装的数据
DatagramPacket dp=new DatagramPacket(buf, 1024);
//创建DatagramSocket对象,接收数据
try {
DatagramSocket ds=new DatagramSocket(8800);
ds.receive(dp);
//显示接收到的数据
String msg=new String(dp.getData(), 0, dp.getLength());
System.out.println(dp.getAddress().getHostAddress()+"说:"+msg);
ds.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
打印信息:
127.0.0.1说:你好,我是用UDP给你发送信息的