import java.io.*;
import java.net.*;
class DataSoketDemo{
public static void main(String[] args)throws Exception{
DatagramSocket se = new DatagramSocket(10000);
//DatagramSocket re = new DatagramSocket(10000);
new Thread(new Send(se)).start();
new Thread(new Rece(se)).start();
}
}
class Send implements Runnable{
private DatagramSocket se;
Send(DatagramSocket se){
this.se= se;
}
public void run(){
DatagramPacket dp;
byte[] buf = "UDP传输协议演示".getBytes();
try {
dp = new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),10000);
se.send(dp);
}
catch(Exception e) {
}
se.close();
}
}
class Rece implements Runnable{
private DatagramSocket re;
Rece(DatagramSocket re){
this.re = re;
}
public void run(){
byte[] buf = new byte[1024];
DatagramPacket dp= new DatagramPacket(buf,buf.length);
try {
re.receive(dp);
}
catch(Exception e) {}
String ip = dp.getAddress().toString();
String data = new String(dp.getData(),0,dp.getData().length);
System.out.println(ip+""+data);
re.close();
}
} |
|