UDP发送端
获取DatagramSocket对象,new出来
获取DatagramPacket对象,new出来,构造参数:byte[]数组,int长度,InetAddress对象,int端口
调用DatagramSocket对象的send()方法,发送出去,参数:DatagramPacket对象
调用DatagramSocket对象的close()方法,关闭资源
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * 发送端 * @author taoshihan * */ public class Sender { public static void main(String[] args) throws Exception { DatagramSocket ds=new DatagramSocket(); byte[] buf="Hello UDP".getBytes(); DatagramPacket p=new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(),10000); ds.send(p); ds.close(); } }
UDP接收端
获取DatagramSocket对象,new出来,构造参数:int端口号
获取DatagramPacket对象,new出来,构造参数:byte[]数组,int长度
调用DatagramSocket对象的receive()方法,接收数据,参数:DatagramPacket对象
调用DatagramPacket对象的getAddress()方法,获取到InetAdress对象
调用DatagramPacket对象的getData()方法,获取到byte[]字节数组,接收的数据
调用DatagramPacket对象的getLength()方法,获取到数据长度
通过new String()包一下,获得String数据,参数:byte[]数组,0开始,length长度
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * 接收端 * @author taoshihan * */ public class Receiver { public static void main(String[] args) throws Exception { DatagramSocket ds=new DatagramSocket(10000); byte[] buf=new byte[1024]; DatagramPacket datagramPacket=new DatagramPacket(buf, buf.length); ds.receive(datagramPacket); InetAddress ip= datagramPacket.getAddress(); int port=datagramPacket.getPort(); byte[] resByte=datagramPacket.getData(); int length=datagramPacket.getLength(); String info=new String(resByte,0,length); System.out.println("来自:"+ip.getHostAddress()+":"+port+"说:"+info); } }
结果:
来自:100.66.217.80:56356说:Hello UDP
先运行接收端,此时程序会阻塞住,等待接收。。。
再运行发送端
接收到一次以后就会断,用while(true) 包一下,死循环但是会阻塞住,注意不要把创建DatagramSocket包进去
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/12681.html