发送端:
package net.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
/*
* 创建UDP发送端的思路:
* 1.建立UDP的Socket服务;使用DatagramSocket
* 2.创建数据包,将要发送的数据封装到数据包;使用DatagramPacket,确定目的地址
* 3.通过UDP的Socket服务发送数据包;send()
* 4.关闭Socket服务
*/
public class UDPSend {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("发送端启动....");
//1.建立UDP的Socket服务;使用DatagramSocket
DatagramSocket ds=new DatagramSocket(8888); //指定发送端端口
//2.创建数据包;使用DatagramPacket,确定目的地址
byte [] buf=new String("Hello,小弟").getBytes();
DatagramPacket dp =
new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.166.193"),10000);
//指定接收端端口
//3.发送数据包;send()
ds.send(dp);
// 4.关闭Socket服务
ds.close();
}
}
接收端:
package net.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/*
* 创建UDP接收端的思路:
* 1.建立UDP的Socket服务;使用DatagramSocket
* 2.创建一个数据包,用于存储接收到的数据。方便用数据包对象的方法解析这些数据。
* 3.使用Socket服务的receive()接收数据并存储到数据包中
* 4.通过数据包对象的方法,解析其中的数据,比如地址,端口,内容等
* 5.关闭Socket服务
*/
public class UDPReceive {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("接收端启动....");
//1.建立UDP的Socket服务;使用DatagramSocket
DatagramSocket ds=new DatagramSocket(10000);
//2.创建一个数据包,用于存储接收到的数据
byte [] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
//3.receive数据
ds.receive(dp);
//4.通过数据包对象的方法,解析其中的数据,比如地址,端口,内容等
String ip=dp.getAddress().getHostAddress();
int port=dp.getPort();
String text=new String (dp.getData(),0,dp.getLength());
//5.关闭Socket服务
System.out.println(ip+"::"+port+"::"+text);
ds.close();
}
}