【Udp的发送端与接收端】
发送端:
- 建立UdpSocket服务
- 提供数据,并将数据封装到数据包中
- 通过socket服务的发送功能,将数据包发送出去
- 关闭资源
接收端:
- 定义UdpSocket服务
- 定义一个数据包,因为要存储接收到的字节数据。因为数据包对象中有更多功能可以提取字节数据中的不同数据信息。
- 通过socket服务的receive方法将收到的数据存入已定义好的数据包中。
- 通过数据包对象的特有功能。将这些不同的数据取出,打印在控制台上。
- 关闭资源
【代码示例】
/*
消息的发送与接受(UDP)
*/
import java.net.*;
//发送端
class UdpSend
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds=new DatagramSocket(8088);
byte[] buf="我是发送端".getBytes();
DatagramPacket dp=new DatagramPacket(
buf,buf.length,InetAddress.getByName("127.0.0.1"),10000);
ds.send(dp);
ds.close();
}
}
//接收端
class UdpReceive
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds=new DatagramSocket(10000);
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
int port=dp.getPort();
System.out.println(ip+"\\"+port+"::"+data);
ds.close();
}
}
【输出截图】
发送端:
接收端: