码迷,mamicode.com
首页 > 编程语言 > 详细

java学习——网络编程

时间:2016-04-18 17:12:10      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

 

 

 

 

 

 

 

 

 

 

未完.....

 

java学习——网络编程

标签:

原文地址:http://www.cnblogs.com/qinwangchen/p/5404823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!