java学习——网络编程UDP

UDP

将数据及源和目的封装成数据包中,不需要建立连接

每个数据报的大小限制在64k内

因无连接,是不可靠协议

不需要建立连接,速度快

TCP

建立连接,形成传输数据的通道

在连接中进行大数据量传输

通过三次握手完成连接,是可靠协议

必须建立连接,效率会稍低 

Ip获取:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPDemo {
    public static void main(String[] args) throws UnknownHostException {

        //获取本地主机ip地址对象。 
        InetAddress ip = InetAddress.getLocalHost();
        
        //获取其他主机的ip地址对象。
        ip = InetAddress.getByName("192.168.1.110");
        //ip = InetAddress.getByName("my_think");
        //ip = InetAddress.getByName("www.baidu.com");
        
        System.out.println(ip.getHostAddress());
        System.out.println(ip.getHostName());
    }
}
View Code

 UDP协议发送端

* 创建UDP传输的发送端。
* 思路:
* 1,建立udp的socket服务。
* 2,将要发送的数据封装到数据包中。
* 3,通过udp的socket服务将数据包发送出去。
* 4,关闭socket服务。

public class UDPSendDemo {
    public static void main(String[] args) throws IOException {
        System.out.println("发送端启动......");   
        //1,udpsocket服务。使用DatagramSocket对象。
        DatagramSocket ds = new DatagramSocket(8888);
        
        //2,将要发送的数据封装到数据包中。
        String str = "udp传输演示:哥们来了!";
            //使用DatagramPacket将数据封装到的该对象包中。
        byte[] buf = str.getBytes();
        
        DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.100"),10000);
        
        //3,通过udp的socket服务将数据包发送出去。使用send方法。
        ds.send(dp);
        
        //4,关闭资源。
        ds.close();    
    }
}
View Code

  UDP协议接收端

* 建立UDP接收端的思路。
* 1,建立udp socket服务,因为是要接收数据,必须要明确一个端口号。
* 2,创建数据包,用于存储接收到的数据。方便用数据包对象的方法解析这些数据.
* 3,使用socket服务的receive方法将接收的数据存储到数据包中。
* 4,通过数据包的方法解析数据包中的数据。
* 5,关闭资源

public class UDPReceDemo {
    public static void main(String[] args) throws IOException {
        System.out.println("接收端启动......");
                
        //1,建立udp socket服务。
        DatagramSocket ds = new DatagramSocket(10000);
            
        //2,创建数据包。
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf,buf.length);
        
        //3,使用接收方法将数据存储到数据包中。
        ds.receive(dp);//阻塞式的。
        
        //4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。
        String ip = dp.getAddress().getHostAddress();
        int port = dp.getPort();
        String text = new String(dp.getData(),0,dp.getLength());
        
        System.out.println(ip+":"+port+":"+text);
        
        //5,关闭资源。
        ds.close();        
    }
}
View Code

 对上述发送端接收端做简单修改,控制台进行输入

Send:

public class UDPSendDemo2 {
    public static void main(String[] args) throws IOException {

        System.out.println("发送端启动......");
        DatagramSocket ds = new DatagramSocket(8888);    
//        String str = "udp传输演示:哥们来了!";
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        
        while((line=bufr.readLine())!=null){        
            byte[] buf = line.getBytes();
            DatagramPacket dp = 
                    new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.100"),10000);
            ds.send(dp);
            
            if("886".equals(line))
                break;
        }        
        //4,关闭资源。
        ds.close();    
    }
}
View Code

Receive:

public class UDPReceDemo2 {
    public static void main(String[] args) throws IOException {

        System.out.println("接收端启动......");
        //1,建立udp socket服务。
        DatagramSocket ds = new DatagramSocket(10000);
        
        while(true){    
        //2,创建数据包。
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf,buf.length);        
        //3,使用接收方法将数据存储到数据包中。
        ds.receive(dp);//阻塞式的。        
        //4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。
        String ip = dp.getAddress().getHostAddress();
        int port = dp.getPort();
        String text = new String(dp.getData(),0,dp.getLength());
        
        System.out.println(ip+":"+port+":"+text);

        }
        //5,关闭资源。
//        ds.close();        
    }
}
View Code

UDP-简单聊天程序:

ChatDemo:

public class ChatDemo {
    public static void main(String[] args) throws IOException {    
        DatagramSocket send = new DatagramSocket();    
        DatagramSocket rece = new DatagramSocket(10001);
        new Thread(new Send(send)).start();
        new Thread(new Rece(rece)).start();    
    }
}
View Code

Receive:

public class Rece implements Runnable {
    private DatagramSocket ds;
    public Rece(DatagramSocket ds) {
        this.ds = ds;
    }
    @Override
    public void run() {
        try {
            while (true) {
                // 2,创建数据包。
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length);

                // 3,使用接收方法将数据存储到数据包中。
                ds.receive(dp);// 阻塞式的。

                // 4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。
                String ip = dp.getAddress().getHostAddress();
                int port = dp.getPort();
                String text = new String(dp.getData(), 0, dp.getLength());
                
                System.out.println(ip + "::" + text);
                if(text.equals("886")){
                    System.out.println(ip+"....退出聊天室");
                }
            }
        } catch (Exception e) {}
    }
}
View Code

Send:

public class Send implements Runnable {
    private DatagramSocket ds;    
    public Send(DatagramSocket ds){
        this.ds = ds;
    }
    @Override
    public void run() {    
        try {
            BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
            String line = null;        
            while((line=bufr.readLine())!=null){
                byte[] buf = line.getBytes();
                DatagramPacket dp = 
                        new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10001);
                ds.send(dp);
                
                if("886".equals(line))
                    break;
            }
            ds.close();
        } catch (Exception e) {}
    }
}
View Code

 

posted @ 2016-04-18 15:59  渣渣的步伐  阅读(186)  评论(0编辑  收藏  举报