import java.net.*;
//发送端
class L
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds=new DatagramSocket(888);
byte[] buf="I love you".getBytes();
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.101"),10000);
ds.send(dp);
ds.close();
}
}
//接收端
class L1
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds=new DatagramSocket(10000);
byte[] buf=new byte[1024];
DatagramPacket dp1=new DatagramPacket(buf,buf.length);
ds.receive(dp1);//阻塞式方法,read()也是阻塞式方法。
String add=dp1.getAddress().getHostAddress();
String name=dp1.getAddress().getHostName();
System.out.println(add);
System.out.println(name);
String all=new String(dp1.getData(),0,dp1.getLength());
int port=dp1.getPort();
System.out.println(all);
System.out.println(port);
ds.close();
}
}
网络编程 发送与接收 代码
最新推荐文章于 2026-01-05 10:01:54 发布
本文提供了一个简单的Java UDP通信示例,包括发送端和接收端的实现代码。发送端通过指定的IP地址和端口发送消息,接收端则监听特定端口并打印接收到的数据及发送方的详细信息。
3万+

被折叠的 条评论
为什么被折叠?



