UDP网络编程原理示意图
UDP说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.study.srv.demo18; import java.io.IOException; import java.net.*; /** * @version 1.0 * UDP发送端 */ public class Demo11 { public static void main(String[] args) throws IOException { //1.创建DatagramSocket对象,准备发送和接收数据,在9998端口接收 DatagramSocket datagramSocket = new DatagramSocket(9998); //2.将需要发送的数据,封装到DatagramPacket对象 String s="发送的数据"; byte[] buf=s.getBytes(); InetAddress ip = InetAddress.getByName("192.168.0.18"); //说明:封装的DatagramPacket对象 //buf 内容字节数组 //buf.length 数据长度 //ip 主机(ip) //9999 端口 DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, 9999); //发送数据 datagramSocket.send(packet); //关闭资源 // datagramSocket.close(); System.out.println("发送完毕"); //发送端变为接收端接收数据 byte[] bytes = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length); datagramSocket.receive(datagramPacket); int length = datagramPacket.getLength(); byte[] data = datagramPacket.getData(); String string = new String(data, 0, length); System.out.println(string); datagramSocket.close(); System.out.println("接受结束"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.study.srv.demo18; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /** * @version 1.0 *UDP接收端 */ public class Demo10 { public static void main(String[] args) throws IOException { //1.创建一个 DatagramSocket对象,准备在9999接收数据 DatagramSocket datagramSocket = new DatagramSocket(9999); //2.构建一个DatagramPacket 对象,准备接收数据 //在UDP协议,一个数据包最大64k byte[] buf=new byte[1024]; DatagramPacket packet = new DatagramPacket(buf, buf.length); //3.接收方法 将通过网络传输的DatagramPacket对象填充到packet里去。 System.out.println("接收端等待接收"); datagramSocket.receive(packet); //4.可以对packet进行拆包,取出数据,并显示 //实际接收到的数据字节长度 int length = packet.getLength(); //实际接收到的数据 byte[] data = packet.getData(); String string = new String(data, 0, length); System.out.println(string); //5.关闭资源 // datagramSocket.close(); System.out.println("接收结束"); //接收端变为发送端,发送数据 String s="接收端变为发送端,发送数据"; byte[] bytes=s.getBytes(); DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("192.168.0.18"), 9998); datagramSocket.send(datagramPacket); datagramSocket.close(); System.out.println("发送完毕"); } } |
到此这篇关于Java UDP编程的文章就介绍到这了,更多相关Java UDP编程内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
from:https://www.jb51.net/article/282201.htm