???????2
??????????
package com.socket.demo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPReceiveDemo2 {
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(10003);
while(true){
//???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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPSendDemo2 {
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(9999);//???????
//???????????????????????
//String str="udp?????????go";
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));//????????
String line=null;
//???DatagramPacket?????????????????
while((line=bufr.readLine())!=null){
byte[] buf=line.getBytes();//
DatagramPacket dp=
new DatagramPacket(buf?? buf.length??InetAddress.getByName("192.168.1.100")??10003);
//???udp??socket????????????????????send????
ds.send(dp);
if("886".equals(line)){
break;
}
}
//??????
ds.close();
}
}
???????Ч?????
????????

????????