发送端:
package com.suncreate.testSocket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Arrays;
public class UdpSend{
public static void main(String[] args){
try {
DatagramSocket datagramSocket = new DatagramSocket(6500);
byte[] buf=new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("-");
DatagramPacket datagramPacket = new DatagramPacket(buf, 10, InetAddress.getByName("172.16.37.162"), 6400);
System.out.println("--");
datagramSocket.send(datagramPacket);
System.out.println("---");
datagramSocket.receive(datagramPacket);
System.out.println(Arrays.toString(buf));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
接收端接收后回复:
package com.suncreate.testSocket;
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.util.Arrays;
public class UdpReply?{ ? ? public static void main(String[] args){ ? ? ? ? try { ? ? ? ? ? ? DatagramSocket datagramSocket = new DatagramSocket(6400); ? ? ? ? ? ? byte[] buf=new byte[10]; ? ? ? ? ? ? DatagramPacket packet= new DatagramPacket(buf,10); ? ? ? ? ? ? datagramSocket.receive(packet); ? ? ? ? ? ? System.out.println(Arrays.toString(buf)); ? ? ? ? ? ? packet.setData(new byte[]{9,8,7,6,5,4,3,2,1,0});
? ? ? ? ? ?//直接修改接收的packet的数据,不用设置ip和port ? ? ? ? ? ? datagramSocket.send(packet); ? ? ? ? } ? ? ? ? catch(Exception e){
? ? ? ? }
? ? } }
|