Java-UDP协议

//接收端
public class ReceiveDemo {
public static void main(String[] args) throws Exception {
	//创建接收对象
	DatagramSocket receiver = new DatagramSocket(18889);
	byte[] buffer =new byte[1024];
	//接收数据
	DatagramPacket dp = new DatagramPacket(buffer,1024);
	receiver.receive(dp);
	//获取接收的数据
	String msg = new String (dp.getData(),0,dp.getLength());
	System.out.println("发送过来的数据:" + msg);
	}
}
//发送端
public class Send {
	public static void main(String[] args) throws Exception {
		String data ="天王盖地虎!";
		//创建发送对象
		DatagramSocket sender = new DatagramSocket(18888);
		//发送数据
		DatagramPacket dp = new DatagramPacket(data.getBytes(),
				data.getBytes().length,
				InetAddress.getLocalHost(),
				19989);
		sender.send(dp);
		sender.close();
	}
}

版权声明:
作者:yfeer
链接:https://yfeer.com/847.html
来源:个人编程学习网
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>