本帖最后由 赵亚威 于 2013-4-2 16:17 编辑
public class SocketDemo {
/**
* @param args
*/
public static void main(String[] args) {
DatagramSocket ds = null;
try {
ds=new DatagramSocket();
byte[] buf="wo shi yi ge shu zu".getBytes();
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10000);
ds.send(dp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(ds!=null)
ds.close();
}
}
}
class SocketRecev{
public static void main(String[] args){
DatagramSocket ds=null;
try {
ds=new DatagramSocket(10000);
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);//port为什么不是10000
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(ds!=null)
ds.close();
}
}
}
运行后的结果:
127.0.0.1:wo shi yi ge shu zu:54397 |