/*
* java socket send and receice demo
* @author:luowen
* @time:2013-11-1
* */
import java.net.*;
class SocketSend
{
public static void main(String[] args)throws Exception
{
//创建socket服务
DatagramSocket ds = new DatagramSocket();
byte[] buf = "yes iam demo".getBytes();
//构造数据包
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),1000);
//发送数据包
ds.send(dp);
ds.close();
}
}
class SocketRece
{
public static void main(String[] args)throws Exception
{
//创建socket服务 坚挺1000端口
DatagramSocket ds = new DatagramSocket(1000);
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by,by.length);
//接受
ds.receive(dp);
String str = "ip:" + dp.getAddress().toString() + "port:" + dp.getPort() + "data:" + new String(dp.getData(),0,dp.getLength());
System.out.println(str);
ds.close();
}
}