Java------网络通信编程 之 菜鸟新手的学习总结

来源:互联网 发布:骨科空心钉 知乎 编辑:程序博客网 时间:2024/06/06 05:16


1、要实现网络传输,需要有什么要求?

   11如何准确定位网络上的一台计算机?

   12如何才能进行可靠的、高效的数据传输?


2Java如何实现网络通信:   InetAddress类的一个对象对应一个Ip地址。

     

      >>ip地址------->>定位一台主机  //唯一的标识Internet上的计算机、 本地回环地址(HostAddress

      >>端口号------->>定位一个应用//标识正在计算机上运行的进程(程序)、

                       不同进程有不同端口号、被定义为一个16位的整数 0~65535其中(0~1023端口被预定                          义,如3306号端口被mysql占用)除非我们需要访问这些特定端口,否则就应该使                                用1024~65535这些端口中的某一个进行通信,以免发生冲突。

                                                                     

      >>Socket(套接字)--------->>端口号和Ip地址的组合。                                                   

3、创建一个InetAddress类的对象:    getByName("域名或ip地址");      

     如:InetAddress  Inet = InetAddress.getByName("127.0.0.1");

            

             获取本机的一个InetAddress类的对象:getLocalHost();   

             

             getAllByName()方法是根据主机名返回其可能的所有InetAddress对象,保存在一个数组中

              

             静态常用的静态方法是getLocalHost(),返回的是本地地址

 

             System.out.println(address);默认调用了InetAddress.toString()方法

 

             

            最为常用的应该是getByName(String host)方法,只需要传入目标主机的名字,InetAddress会尝试做             连接DNS服务器,并且获取IP地址的操作

 

             

           3.2. InetAddress对象的获取:

 

               InetAddress的构造函数不是公开的(public),所以需要通过它提供的静态方法来获取

                有以下的方法:

 

                static InetAddress[] getAllByName(Stringhost)

 

                static InetAddress getByAddress(byte[]addr)

 

                static InetAddress getByAddress(Stringhost,byte[] addr)

 

                static InetAddress getByName(String host)

 

                static InetAddress getLocalHost()

 

               域名:   getHostName();          Ip   getHostAddress();

              

               public class TestInetAddress {

       public static void main(String[] args) throws Exception {

//获取本机的域名及ip地址
InetAddress inet = InetAddress.getLocalHost();
//InetAddress inet = InetAddress.getByName("www.baidu.com");
System.out.println(inet);
System.out.println(inet.getHostName());
System.out.println(inet.getHostAddress());

System.out.println("-------------------------------");


//在getAllByName()方法中,获取在该域名下所有的ip地址
InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");


for (InetAddress addr : addresses) {
System.out.println(addr);
System.out.println(addr.getHostName());
System.out.println(addr.getHostAddress());
}
        }
                }

 4、网络传输:

       TCP/Ip参考模型     应用层---------->>   HTTP  FTP  Telnet    DNS(域名解析服务器)

                            传输层---------->>   TCP   UDP                                                                         网络层---------->>   IP   ICMP   ARP

                       物理+链路层---------->>   LINK

                   封装:  从应用层---------->>   物理+链路层         

                    拆封从物理+链路层 ---->>   应用层

5、网络通信协议

     Ⅰ、TCP(TransmissionContronlProtocol)传输控制协议Socket    ServerSocket

            

         >>客户端:主动发起通信的应用程序

                   

        @Test
        public void client(){
        

                Socket socket=null;
                OutputStream os=null;

               try {   //创建一个socket对象 指明服务端的地址和端口号
                       socket = new Socket(InetAddress.getByName("localhost"),6969);
                       //创建一个输出流,发送请求的内容
                       os = socket.getOutputStream();
                       os.write("我是客户端向你发送请求".getBytes());

                       } catch (Exception e) {
                            e.printStackTrace();
                       } 

                       //确保输出流和socket能够关闭
                       finally{

                             if(os!=null){
                           try {
                                 os.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }}
                             if(socket!=null){
                           try {
                                 socket.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }}
                                }

          >>服务端:等待通信请求处理和反馈信息给客户端:

           

            @Test
            public void server(){

                     ServerSocket ss=null;
                     Socket s=null;
                     InputStream is=null;

                try {   //创建一个ServerSocket对象 指明端口号用来监听客户端发送的请求
                        ss = new ServerSocket(6969);

                        //创建一个socket对象 来接收客户端的请求
                        s = ss.accept();

                        //获取输入流
                        is = s.getInputStream();
                        //接收并打印该输入流
                        byte[] b = new byte[1024];
                        int len;
                        String str=null;
                        while ((len = is.read(b))!=-1){
                        String str1 = new  String(b,0,len);
                        str+=str1;
                        system.out.println(str);
                       }
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                       //确保输出流和socket能够关闭
                       finally{

                          if(is!=null){
                       try {
                             is.close();
                           } catch (IOException e) {
                               e.printStackTrace();
                           }}
                         if(s!=null){
                      try {
                            s.close();
                           } catch (IOException e) {
                               e.printStackTrace();
                           }}
                        if(ss!=null){
                      try {
                            ss.close();
                           } catch (IOException e) {
                               e.printStackTrace();
                           }}
                           }

     Ⅱ、UDP(UeserDatagramProtocol)用户数据表协议 DatagramSocket    DatagramPacket

            >> UDP数据报通过数据报套接字DatagramSocket发送和接收,系统不能保证udp数据报一定

                能够安全送到目的地,也不能确定什么时候抵达。

            >>DatagramPacket对象封装了udp数据报,在数据报中包含了发送端的ip地址和端口号以及

                接收端的ip地址和端口号。

            >>每个数据报不能大于64k.

           >> udp协议中每个数据报都给出了完整的地址信息,因此无需建立发送方和接收方的连接。

             

             >>发送端:主动发起通信的应用程序

             

                @Test

                public void send(){

              

                 DatagramSocket ds=null;


                 try {   //创建一个DatagramSocket对象
                         ds = new  DatagramSocket();
                         //用字节数组发送内容
                         byte[] b = "你好我是发送端".getBytes();
                         //打包发送的内容
                         DatagramPacket  dp =new DatagramPacket(b,0,b.length,
                         InetAddress.getByName("localhost"),9090);
                         //发送打包的内容
                         ds.send(dp);
                         } catch (SocketException e) {
                             e.printStackTrace();
                         } catch (UnknownHostException e) {
                             e.printStackTrace();
                         } catch (IOException e) {
                             e.printStackTrace();
                         }
                         //确保发送端能够关闭
                         finally{
                            if(ds!=null){
                               ds.close();
                         }
                         }}

            >>接收端:

           

                @Test
                public void receive(){ 

                     
                DatagramSocket ds=null;


                try {    //创建一个DatagramSocket对象
                         ds = new  DatagramSocket(9090);
                         //用字节数组来接收发送端的内容
                         byte[] b = new byte[1024];
                         //获取打包过来的内容
                         DatagramPacket  dp =new DatagramPacket(b,0,b.length);
                         //接收并打印打包过来的内容
                         ds.receive(dp);
                         String str = new String(dp.getData(),0,dp.getLength());
                         System.out.println(str);


                         } catch (SocketException e) {
                             e.printStackTrace();
                         } catch (IOException e) {
                             e.printStackTrace();
                         }
                         //确保接收端能够关闭
                         finally{
                            if(ds!=null){
                               ds.close();
                         }
                         }
                         }   

      Ⅲ、TCP/Ip协议:传输控制协议和网络互联协议,他们是一组协议,包括具有不同功能且互为关联。

      

      Ⅳ、IPInternet  Protocol)协议是网络层的主要协议支持网间互联的数据通信。

          通信的两端都要有Socket,他是两台计算机间通信的端点。网络通信其实就是Socket的通信。

           Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO流传输。

     

      Ⅴ、URL(UniformResouceLocation)统一资源定位符internet上某一资源的地址,即连接

           URL的基本结构由五个部分组成:

           

          >>《传输协议》://《主机名》:《端口号》/《文件名》

           >>例如:http://127.0.0.1:8080/helloworld/index.jsp

           

            @Test
    public void testurl() throws Exception{

  //创建一个url的对象
       //URL url = new URL("资源的路径");

 URL url = new URL("资源的路径");

   //url的方法
System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPort());
System.out.println(url.getFile());
System.out.println(url.getRef());
System.out.println(url.getPath());
System.out.println(url.getQuery());
System.out.println(url.getDefaultPort());
 
//如何将服务端的资源读取进来openStream()
InputStream is = url.openStream();
byte[] b = new byte[20];
int len;
while((len=is.read(b)) != -1){
String str = new String(b,0,len);
System.out.println(str);
}
is.close();
 
//如果既有数据输入又有数据输出,URLConnection   写到一个文件里
URLConnection urlconn = url.openConnection();
InputStream is1 = urlconn.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("路径"));
byte[] b1 = new byte[20];
int len1;
while((len1 = is1.read(b1)) != -1){
fos.write(b1, 0, len1);
}
fos.close();
is1.close();
}
}

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 记事本回车键不能换行怎么办 网页xml 载入失效怎么办 网页没有搜索栏怎么办 咖喱调料打开了怎么办 煮咖喱水放多了怎么办 营业执照4年没用怎么办 刷赞网站打不开怎么办 网页界面变大了怎么办 照片在易企秀放不完整怎么办 易企秀审核未通过怎么办 微信文件过期怎么办 商家一直不退款怎么办 商家不退运费怎么办 电源标签没了怎么办 淘宝退货的邮费怎么办 淘宝店铺未授权怎么办 商家收款不发货怎么办 厂家收款不发货怎么办 微信支付没到账怎么办 二维码被涂了怎么办 手机老是卡顿怎么办 买完东西降价怎么办 买家不补邮费怎么办 win10网络初始化失败怎么办 win10电脑初始化失败怎么办 获取ip地址失败怎么办 oppor11开不了机怎么办 拼多多商家发错货怎么办 刷好评兼职骗怎么办 公司不想经营了怎么办 外地开公司手续怎么办 淘宝周平均值5.8怎么办 店铺宝贝降权怎么办 淘宝链接被屏蔽怎么办 闲鱼宝贝被降权怎么办 淘宝店没有订单怎么办 拼多多被降权了怎么办 oppo手机流量卡怎么办 刷好评兼职被骗怎么办 淘宝客服态度不好怎么办 电脑显示系统错误怎么办