public class UdpSend {
/**
* 发送的代码
*/
public static void main(String[] args)throws Exception {
DatagramSocket ds=new DatagramSocket();
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while((line=buf.readLine())!=null){
if("886".equals(line)){
break;
}
byte[] da=line.getBytes();
DatagramPacket dp=new DatagramPacket(da, da.length,InetAddress.getByName("192.168.100.11"),8080);
ds.send(dp);
}
ds.close();
}
}
//接收的代码
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceive {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
DatagramSocket ds=new DatagramSocket(8080);
while(true){
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip= dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
int port=dp.getPort();
System.out.println("我收到的信息"+ip+":"+data+":"+port);}
}
}
|
|