网络通信2

TestTCP3

package com.aff.internet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

//TCP编程3:客户端给发文件给服务端,服务端保存到本地并返回 "你发送的图片已接收成功" 给客户端,并关闭相应的连接
//如下的程序处理异常时要使用try-catch-finally,流等是稀有资源
public class TestTCP3 {
    // 客户端
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        InputStream is = null;
        try {
            // 1.创建一个socket的对象,通过构造器指明服务端的ip地址,以及接收程序的端口号
            socket = new Socket(InetAddress.getByName("192.168.3.10"), 9090);
            os = socket.getOutputStream();
            // 从本地获取一个文件发送给服务器
            fis = new FileInputStream(new File("1.jpg"));
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                // 把文件读进来然后写出去就是发送给服务端
                os.write(b, 0, len);
            }
            socket.shutdownOutput();
            // 3.接收服务端发来的信息
            is = socket.getInputStream();
            byte[] b1 = new byte[1024];
            int len1;
            while ((len1 = is.read(b1)) != -1) {
                String str = new String(b1, 0, len1);
                System.out.println(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭相应的流和Socket对象
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.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;
        OutputStream os = null;
        FileOutputStream fos = null;
        try {
            // 1.创建一个ServerSocket的对象,通过构造器指明自身的端口号
            ss = new ServerSocket(9090);
            // 2.调用其accept()方法,返回一个Socket对象
            s = ss.accept();
            // 3.调用Socket对象的getInputStream()获取一个从客户端发送过来的输入流
            is = s.getInputStream();
            // 4.保存到本地
            fos = new FileOutputStream(new File("2.jpg"));
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            // 5发送接收成功信息反馈给客户端
            os = s.getOutputStream();
            os.write("你发送的图片已接收成功".getBytes());
            System.out.println("收到来自于" + s.getInetAddress().getHostAddress() + "的文件");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 6.关闭相应的流以及Socket, ServerSocket对象
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            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网络通信:

       ①类 DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序。
       ②UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证UDP数据报一定能够安全送到目的地,

          也不能确定什么时候可以抵达。
       ③DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号

           以及接收端的IP地址和端口号。
       ④UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接

流 程:
                 ①DatagramSocket与DatagramPacket
                 ② 建立发送端,接收端
                 ③建立数据包
                 ④调用Socket的发送、接收方法
                 ⑤关闭Socket
注意:发送端与接收端是两个独立的运行程序

TestUDP

package com.aff.internet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.junit.Test;

public class TestUDP {
    // 发送端
    @Test
    public void send() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket();
            byte[] b = "我是要发送的数据".getBytes();
            // 创建一个数据报: 每一个数据报不能大于64k,都记录着数据信息,
            // 发送端的IP,端口号,以及要发送到的接收端的IP,端口号
            DatagramPacket pack = new DatagramPacket(b, 0, b.length, InetAddress.getByName("192.168.3.10"), 9090);
            ds.send(pack);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
    }

    // 接收端
    @Test
    public void receive() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(9090);
            byte[] b = new byte[1024];
            DatagramPacket pack = new DatagramPacket(b, 0, b.length);
            ds.receive(pack);
            String str = new String(pack.getData(), 0, pack.getLength());
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
    }
}

 

URL编程

 

          URL:统一资源定位符,一个URL的对象,对应互联网上的一个资源
          我们可以通过url的对象调用其相应的方法,将此资源读取(下载)

 

            URL(Uniform Resource Locator):统一资源定位符,它表示 Internet 上某一资源的地址。

            通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www,ftp 站点。

            浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。 

1.URL的基本结构由5部分组成:

            <传输协议>://<主机名>:<端口号>/<文件名>
           例如: http://192.168.1.100:8080/helloworld/index.jsp


2.为了表示URL,java.net 中实现了类 URL。

    我们可以通过下面的构造器来初始化一个 URL 对象:
            public URL (String spec):通过一个表示URL地址的字符串可以构造一个URL对象。

                                                       例如:URL url = new URL ("http://www. atguigu.com/");
            public URL(URL context, String spec):

                                                       通过基 URL 和相对 URL 构造一个 URL 对象。

                                                       例如:URL downloadUrl = new URL(url, “download.html")
            public URL(String protocol, String host, String file);

                                                        例如:new URL("http", "www.atguigu.com", “download. html");
            public URL(String protocol, String host, int port, String file);

                                                        例如: URL gamelan = new URL("http", "www.atguigu.com", 80, “download.html");

3.  一个URL对象生成后,其属性是不能被改变的,

     但可以通过它给定的方法来获取这些属性:
                            public String getProtocol( ) 获取该URL的协议名
                            public String getHost( ) 获取该URL的主机名
                            public String getPort( ) 获取该URL的端口号
                            public String getPath( ) 获取该URL的文件路径
                            public String getFile( ) 获取该URL的文件名
                            public String getRef( ) 获取该URL在文件中的相对位置
                            public String getQuery( ) 获取该URL的查询名

注意:类URL的构造方法都声明抛出非运行时异常,必须要对这一异常进行处理,

           通常是用 try-catch 语句进行捕获。

 

URLConnection类

           通过URLConnection对象获取的输入流和输出流,即可以与现有的CGI程序进行交互。
                            public Object getContent( ) throws IOException
                            public int getContentLength( )
                            public String getContentType( )
                            public long getDate( )
                            public long getLastModified( )
                            public InputStream getInputStream( )throws IOException
                            public OutputSteram getOutputStream( )throws IOException

小结:

            ①TCP协议用于实现面向连接的会话。

            ②Java 中有关网络方面的功能都定义在 java.net 程序包中。

               Java 用 InetAddress 对象表示 IP 地址,

              该对象里有两个字段:主机名(String) 和 IP 地址(int)。

           ③类 Socket 和 ServerSocket 实现了基于TCP协议的客户端-服务器程序。

                Socket是客户端和服务器之间的一个连接,连接创建的细节被隐藏了。

                这个连接提供了一个安全的数据传输通道,

                这是因为 TCP 协议可以解决

                数据在传送过程中的丢失、损坏、重复、乱序以及网络拥挤等问题,

               它保证数据可靠的传送。

            ④类 URL 和 URLConnection 提供了最高级网络应用

            ⑤位于网络中的计算机具有唯一的IP地址,这样不同的主机可以互相区分。

posted @ 2020-04-04 00:16  林淼零  阅读(122)  评论(0编辑  收藏  举报