???????1
??????????
package com.socket.demo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPReceiveDemo {
public static void main(String[] args) throws IOException{
System.out.println("????????…………");
/*
2??????UDP??socket?????????????????????
3????????????????????????????????????????????????????????Щ????
4?????DatagramSocket??receive?????????????????洢?????????
5?????????????????????????е?????
5?????socket????
*/
//udpsocket???????DatagramSocket????
DatagramSocket ds=new DatagramSocket(10002);
//???DatagramPacket?????????????????
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf?? buf.length);
//???udp??socket????????????????????send????
ds.receive(dp);
//???????????????????????е?????????????????????????????
String ip=dp.getAddress().getHostAddress();
//String name=dp.getAddress().getHostName();
int port=dp.getPort();
String text=new String(dp.getData()??0??dp.getLength());
//System.out.println("-----"+ip+"-----"+name+"-----"+port+"-----"+text);
System.out.println("-----"+ip+"----------"+port+"-----"+text);
//??????
ds.close();
}
}
??????????
package com.socket.demo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDPSendDemo {
public static void main(String[] args) throws IOException{
System.out.println("????????…………");
/*
*  1??????udp?????????
2??????UDP??socket?????
3?????????????????????????
4?????udp??socket???????????????
5?????socket????
*/
//udpsocket???????DatagramSocket????
DatagramSocket ds=new DatagramSocket(8888);//???????
//???????????????????????
String str="udp?????????go";
//???DatagramPacket?????????????????
byte[] buf=str.getBytes();
DatagramPacket dp=
new DatagramPacket(buf?? buf.length??InetAddress.getByName("192.168.1.100")??10002);
//???udp??socket????????????????????send????
ds.send(dp);
//??????
ds.close();
}
}