为方便对比,我把发送端与接收端写在了同一个文件中
import java.net.*;
class UdpSend
{
public static void main(String[] args) throws Exception
{
//1.建立udp服务,通过DatagramSocket对象
DatagramSocket ds = new DatagramSocket();
//2.确定数据,并封装成数据包
//DatagramPacket(byte[] buf,int length,InetAddress address,int port)
byte[] buf = "udp ge men lai le ".getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.235.128"),10000);
//3.通过socket服务,将已有的数据包发送出去,通过send方法
ds.send(dp);
//4.关闭资源
ds.close();
}
}
/*
需求:
定义一个应用程序,用于接收udp协议传输的数据并处理。
思路:
1.定义udpsocket服务,监听一个端口,给这个接收网络应用程序定义数字标识
2.定义一个数据包,因为要存储接收到的字节数据,因为数据包对象中有更多功能
可以提取字节数据中的不同数据信息
3.通过socket服务的receive方法将收到的数据存入已定义好的数据包中
4.通过数据包对象的特有功能,将这些不同的数据取出,打印在控制台上
5.关闭资源
*/
class UdpReceive
{
public static void main(String[] args) throws Exception
{
//1.创建udp socket,建立断点
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();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println(ip+"::"+data+"::"+port);
//5.关闭资源
ds.close();
}
}
修改上面例子,使其可以通过键盘录入方式进行输入要发送的数据。
此外,修改后的例子是通过广播方式发送数据,处于同一个局域网的主机,只要绑定的端口一致,均可接收到数据。
import java.net.*;
import java.io.*;
class UdpSend
{
public static void main(String[] args) throws Exception
{
//1.建立udp服务,通过DatagramSocket对象
DatagramSocket ds = new DatagramSocket();
//2.确定数据,并封装成数据包
//DatagramPacket(byte[] buf,int length,InetAddress address,int port)
//byte[] buf = "udp ge men lai le ".getBytes();
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=bufr.readLine()) != null)
{
if("886".equals(line))
break;
byte[] buf = line.getBytes();
//主机号为全1的ip地址为广播地址
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.235.255"),10000);
//3.通过socket服务,将已有的数据包发送出去,通过send方法
ds.send(dp);
}
//4.关闭资源
ds.close();
}
}
/*
需求:
定义一个应用程序,用于接收udp协议传输的数据并处理。
思路:
1.定义udpsocket服务,监听一个端口,给这个接收网络应用程序定义数字标识
2.定义一个数据包,因为要存储接收到的字节数据,因为数据包对象中有更多功能
可以提取字节数据中的不同数据信息
3.通过socket服务的receive方法将收到的数据存入已定义好的数据包中
4.通过数据包对象的特有功能,将这些不同的数据取出,打印在控制台上
5.关闭资源
*/
class UdpReceive
{
public static void main(String[] args) throws Exception
{
//1.创建udp socket,建立断点
DatagramSocket ds = new DatagramSocket(10000);
while(true)
{
//2.定义数据包,用于存储数据
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
//3.通过服务的receive将收到的数据存入数据包中
ds.receive(dp);
//4.通过数据包的方法获取其中的数据
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
int port = dp.getPort();
System.out.println(ip+"::"+data+"::"+port);
}
//5.关闭资源
//ds.close();
}
}