本文主要是介绍UDP网络编程的接受与发送信息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/发送端B===>可以接受数据
public class UDPSenderB {public static void main(String[] args) throws IOException {//创建一个DatagramSocket 对象,准备发送和接受数据DatagramSocket socket = new DatagramSocket(9998);//将需要发送的数据,封装到DatagramPacket对象byte[] data = "hello “明天吃火锅~".getBytes();DatagramPacket packet = new DatagramPacket(data, 0, data.length, InetAddress.getLocalHost(), 9999);socket.send(packet);//现在接受A发送的信息data = packet.getData();int len = packet.getLength();packet = new DatagramPacket(data, data.length);socket.receive(packet);String s = new String(data,0,len);System.out.println(s);System.out.println("UDPB端已经退出~");//关闭资源socket.close();}
}
public class UDPReceiverA {public static void main(String[] args) throws IOException {//1.创建一个DatagramSocket 对象,准备在9999接收数据DatagramSocket socket = new DatagramSocket(9999);//2.构建一个DatagramPacket对象,准备接受数据//一个数据包最大为64K===>2^16-1byte[] buf = new byte[1024];DatagramPacket packet = new DatagramPacket(buf, buf.length);//3.调用接受方法,将通过网络传输的DatagramPacket对象//填充到packet对象System.out.println("正在等待接收数据...");socket.receive(packet);//现在将数剧进行解包int len = packet.getLength();byte[] bytes = packet.getData();String s = new String(bytes,0,len);System.out.println("接收到的数据为:"+s);//现在发送数据byte[] bytes1 = "好的,明天见!".getBytes();DatagramPacket packet1 =new DatagramPacket(bytes1,0,bytes1.length, InetAddress.getLocalHost(),9998);socket.send(packet1);System.out.println("UDPA端已经退出~");//关闭数据流socket.close();}
}
这篇关于UDP网络编程的接受与发送信息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!