黑马程序员技术交流社区

标题: 记录-Udp传输 [打印本页]

作者: 不怕黑人    时间: 2015-7-13 12:53
标题: 记录-Udp传输
import java.net.*;
class SendData
{
        public static void main(String[] args) throws Exception
        {
                DatagramSocket ds=new DatagramSocket(1456);
                byte[] buf="发送一个数据".getBytes();
                DatagramPacket ap=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10000);
                ds.send(ap);
                ds.close();
        }
}
class ReceiveData
{
        public static void main(String[] args) throws Exception
        {
                DatagramSocket 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);
                ds.close();
        }
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2