Java Socket传输数据与 Url类

Socket

所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端

 利用套接字(Socket)开发网络应用程序早已被广泛的采用,以至于成为事实 上的标准。

 网络上具有唯一标识的IP地址和端口号组合在一起才能构成唯一能识别的标 识符套接字。

 通信的两端都要有Socket,是两台机器间通信的端点。

 网络通信其实就是Socket间的通信。

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

 一般主动发起通信的应用程序属客户端,等待通信请求的为服务端。

Socket的分类

流套接字(stream socket): 使用TCP提供可依赖的字节流服务 
数据报套接字(datagram socket): 使用UDP提供“尽力而为”的数据报服务

Socket的操作

 Socket类的常用构造器:
     public Socket(InetAddress address,int port)创建一个流套接字并将其连接到指定 IP 地址的指定端口号。 
     public Socket(String host,int port)创建一个流套接字并将其连接到指定主机上的指定端口号。
 Socket类的常用方法:
     public InputStream getInputStream()返回此套接字的输入流。可以用于接收网络消息
     public OutputStream getOutputStream()返回此套接字的输出流。可以用于发送网络消息
     public InetAddress getInetAddress()此套接字连接到的远程 IP 地址;如果套接字是未连接的,则返回 null。
     public InetAddress getLocalAddress()获取套接字绑定的本地地址。 即本端的IP地址
     public int getPort()此套接字连接到的远程端口号;如果尚未连接套接字,则返回 0。
     public int getLocalPort()返回此套接字绑定到的本地端口。 如果尚未绑定套接字,则返回 -1。即本端的
端口号。
     public void close()关闭此套接字。套接字被关闭后,便不可在以后的网络连接中使用(即无法重新连接
或重新绑定)。需要创建新的套接字对象。 关闭此套接字也将会关闭该套接字的 InputStream 和
OutputStream。
     public void shutdownInput()如果在套接字上调用 shutdownInput() 后从套接字输入流读取内容,则流将
返回 EOF(文件结束符)。 即不能在从此套接字的输入流中接收任何数据。
     public void shutdownOutput()禁用此套接字的输出流。对于 TCP 套接字,任何以前写入的数据都将被发
送,并且后跟 TCP 的正常连接终止序列。 如果在套接字上调用 shutdownOutput() 后写入套接字输出流, 则该流将抛出 IOException。 即不能通过此套接字的输出流发送任何数据。

基于Socket的Tcp编程

Java语言的基于套接字编程分为服务端编程和客户端编程,其通信模 型如图所示:

客户端Socket的工作过程包含以下四个基本的步骤:

 创建 Socket:根据指定服务端的 IP 地址或端口号构造 Socket 类对象。若服务器端 响应,则建立客户端到服务器的通信线路。若连接失败,会出现异常。

 打开连接到 Socket 的输入/出流: 使用 getInputStream()方法获得输入流,使用 getOutputStream()方法获得输出流,进行数据传输

按照一定的协议对Socket 进行读/写操作:通过输入流读取服务器放入线路的信息 (但不能读取自己放入线路的信息),通过输出流将信息写入线程。

 关闭 Socket:断开客户端到服务器的连接,释放线路
客户端程序可以使用Socket类创建对象,创建的同时会自动向服务器方发起连 接。Socket的构造器是:
    Socket(String host,int port)throws UnknownHostException,IOException:向服务器(域名是 host。端口号为port)发起TCP连接,若成功,则创建Socket对象,否则抛出异常。
    Socket(InetAddress address,int port)throws IOException:根据InetAddress对象所表示的 IP地址以及端口号port发起连接。


  客户端建立socketAtClient对象的过程就是向服务器发出套接字连接请求

Socket s = new Socket(“192.168.40.165”,9999); 
OutputStream out = s.getOutputStream(); out.write(" hello".getBytes());
s.close();

指定服务端ip和端口的时候可以使用new  Socket(ip,端口)也可以借助InetAddress来完成

 /**
     *  实现TCP的网络编程
     *  * 例子1:客户端发送信息给服务端,服务端将数据显示在控制台上
     * @param args
     */
    public static void main(String[] args) {
        Socket socket = null;  // 使用socket建立服务端
        OutputStream os  = null;
        try {
            //1  创建Socket对象指明 服务端ip和端口
            InetAddress inetAddress = InetAddress.getByName("192.168.1.10");  // 指定服务端的ip地址
            socket = new Socket(inetAddress,8899);

            // 2 : socket获取一个输出流 用于输出数据
            os = socket.getOutputStream();

            // 3 :写出数据

            os.write("老王我是客户端来请求你".getBytes());
        } catch (IOException e) {
            e.printStackTrace();

            //4 :资源的关闭, 关闭流和socket
        } finally {
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

服务端Socket的工作过程包含以下四个基本的步骤:

调用 ServerSocket(int port) :创建一个服务器端套接字,并绑定到指定端口
   上。用于监听客户端的请求。
调用 accept():监听连接请求,如果客户端请求连接,则接受连接,返回通信 套接字对象。
调用 该Socket类对象的 getOutputStream() 和 getInputStream ():获取输出 流和输入流,开始网络数据的发送和接收。
关闭ServerSocket和Socket对象:客户端访问结束,关闭通信套接字。

服务器建立 ServerSocket 对象

ServerSocket 对象负责等待客户端请求建立套接字连接,类似邮局某个窗口 中的业务员。也就是说,服务器必须事先建立一个等待客户请求建立套接字 连接的ServerSocket对象。
所谓“接收”客户的套接字请求,就是accept()方法会返回一个 Socket 对象

ServerSocket ss = new ServerSocket(9999); Socket s = ss.accept ();
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int num = in.read(buf);
String str = new String(buf,0,num); System.out.println(s.getInetAddress().toString()+”:”+str); s.close();
ss.close();

server端取数据尽量使用ByteArrayOutputStream因为它会在内部建立一个缓冲区先将数据存储到缓冲区,等数据获取完毕一次输出,不会因为外部建的数组不够大导致数据乱码

public class TcpTestOneServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream bo = null;

        try {
            // 1.创建服务器端的ServerSocket,指明自己的端口号
            serverSocket = new ServerSocket(8899);
            // 2.调用accept()表示接收来自于客户端的socket
            socket = serverSocket.accept();

            // 获取输入流
            is = socket.getInputStream();

            /*  这样写有可能乱码  : 输出结果  老王我是客户��来请求你
            byte [] bytes = new byte[20];
            int len;
            while ((len = is.read(bytes)) != -1){
                String str = new String(bytes,0,len);
                System.out.print(str);
            }
*/
           bo = new  ByteArrayOutputStream();
           byte [] buffer = new byte[5];
           int len;
           while ((len = is.read(buffer)) != -1){
               bo.write(buffer,0,len);
           }
            System.out.println(bo.toString());
            System.out.println("/接收到了 来自"+socket.getInetAddress().getHostAddress()+"的数据");

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

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

    }
}

Socket通信的理解

socket通信好比你去邮局寄快递,socket就是邮局,个人是client端,server是你的邮寄对象(your feriends),

client在邮寄的时候先要获取到server的地址,也就是ip和端口就好比你朋友的小区和门牌号,

这样才能精准的找到目标,然后将要写的数据通过邮局,也就是输出流邮局socket将你要写的数据通过OutputStream信封把数据存储起来,然后发送,你要发送的数据都存储在邮局的信封内:Socket.OutputStream()中.

Server你的朋友在收取数据的时候要先在家等着才能收到信封,所以将朋友在家的状态设为ServerSocket,朋友除了在家还要同意接受信封而不是拒收,所以朋友同意的状态是基于在家的前提那就是

serverSocket.accept();那么就可以将信封给你了拿到信封 Socket.InputStream(),然后就是拆信封ByteArrayOutputStream()读取数据

在传输数据的时候  服务端在接收数据使用read()的时候,会进行阻塞,因为client端没有传递给一个确切的断开连接的信息,所以client在使用socket传输数据的时候不仅仅要关闭socket还要告诉

  server端什么时候数据传输完毕要关闭连接 使用socket.shutdownOutput()关闭输出,不然server端还在等着你的传输不会进行下面的步骤server会卡住

Tcp-Practices

客户端发送文件给服务端,服务端将文件保存在本地。
client

    public static void main(String[] args) {
        Socket socket = null;
        OutputStream osSix = null;
        FileInputStream fileInputStream = null;
        try {
            socket = new Socket("192.168.1.10",1005);
            osSix = socket.getOutputStream();
            fileInputStream = new FileInputStream(new File("beauty.jpg")); // 操作文件用到字节流来

            byte [] bytes = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1){
                osSix.write(bytes,0,len);
            }

            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

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

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



    }
client

server

public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fw = null;
        try {
            serverSocket = new ServerSocket(1005);
            socket = serverSocket.accept();
            is = socket.getInputStream();
            fw = new FileOutputStream("beautyThree.jpg");

            byte [] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1){
                fw.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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


    }
server
2:从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。
    /*
        这里涉及到的异常,应该使用try-catch-finally处理
         */
    @Test
    public void client() throws IOException {
        //1.
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        //2.
        OutputStream os = socket.getOutputStream();
        //3.
        FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
        //4.
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //关闭数据的输出
        socket.shutdownOutput();

        //5.接收来自于服务器端的数据,并显示到控制台上
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferr = new byte[20];
        int len1;
        while((len1 = is.read(buffer)) != -1){
            baos.write(buffer,0,len1);
        }

        System.out.println(baos.toString());

        //6.
        fis.close();
        os.close();
        socket.close();
        baos.close();
    }

    /*
    这里涉及到的异常,应该使用try-catch-finally处理
     */
    @Test
    public void server() throws IOException {
        //1.
        ServerSocket ss = new ServerSocket(9090);
        //2.
        Socket socket = ss.accept();
        //3.
        InputStream is = socket.getInputStream();
        //4.
        FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
        //5.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }

        System.out.println("图片传输完成");

        //6.服务器端给予客户端反馈
        OutputStream os = socket.getOutputStream();
        os.write("你好,美女,照片我已收到,非常漂亮!".getBytes());

        //7.
        fos.close();
        is.close();
        socket.close();
        ss.close();
        os.close();

    }
View Code

这里涉及交互的问题需要用到socket.shutdownOutput() 来通知对方已经传递完数据

3: .服务端读取图片并发送给客户端,客户端保存图片到本地

 @Test
    public void TcpTestThreeClient(){
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            socket = new Socket("127.0.0.1",1002);
            is = socket.getInputStream();
            fos = new FileOutputStream("aTcp.jpg");
            int len;
            byte [] bytes = new byte[1024];
            while ((len = is.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

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


    @Test
    public void TcpTestThreeServer(){
        ServerSocket serverSocketThree = null;
        Socket socketThree = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            serverSocketThree = new ServerSocket(1002);
            socketThree = serverSocketThree.accept();
            os = socketThree.getOutputStream();
            fis = new FileInputStream("a.jpg");
            int len;
            byte [] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1){
                os.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if(serverSocketThree != null){
                try {
                    serverSocketThree.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(socketThree != null){
                try {
                    socketThree.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
.服务端读取图片并发送给客户端,客户端保存图片到本地

4: .客户端给服务端发送文本,服务端会将文本转成大写在返回给客户端。

    @Test
    public void TcpTestFourClient(){
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        try {
            socket = new Socket("127.0.0.1",1003);
            os = socket.getOutputStream();
            os.write("I'm laowang".getBytes());
            socket.shutdownOutput();  // 关闭数据类的输出不然server.read()会一直阻塞等待接受数据,因为你下面还在等待接受数据并没有关闭socket server会误认为你还要发送
            is = socket.getInputStream();
            int len;
            byte [] bytes = new byte[5];
            bos = new ByteArrayOutputStream();
            while ((len = is.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }

            System.out.println(bos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

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

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

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

    }

    @Test
    public void TcpTestFourServer(){
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream  is= null;
        OutputStream os = null;
        ByteArrayOutputStream bos = null;
        try {
            serverSocket = new ServerSocket(1003);
            socket = serverSocket.accept();
            is = socket.getInputStream();
            os = socket.getOutputStream();
            bos = new ByteArrayOutputStream();
            int len;
            byte [] bytes = new byte[5];
            while ((len = is.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
            System.out.println("接到了来组客户端的信息");
            String str = bos.toString().toUpperCase();
            System.out.println(str);

            os.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

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

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

        }


    }
.客户端给服务端发送文本,服务端会将文本转成大写在返回给客户端。

UDP网络通信

类 DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序

UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证 UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。 

 DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP 地址和端口号以及接收端的IP地址和端口号。 

UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和 接收方的连接。如同发快递包裹一样

可以理解为udp为了追求效率不在乎对方是否收到 只发送自己所需要发送的内容

DatagramSocket 类的常用方法

public DatagramSocket(int port)创建数据报套接字并将其绑定到本地主机上的指定端口。套接字将被 绑定到通配符地址,IP 地址由内核来选择。 

 public DatagramSocket(int port,InetAddress laddr)创建数据报套接字,将其绑定到指定的本地地址。 本地端口必须在 0 到 65535 之间(包括两者)。如果 IP 地址为 0.0.0.0,套接字将被绑定到通配符地 址,IP 地址由内核选择。 

 public void close()关闭此数据报套接字。
 
 public void send(DatagramPacket p)从此套接字发送数据报包。DatagramPacket 包含的信息指示:将 要发送的数据、其长度、远程主机的IP 地址和远程主机的端口号。 
 public void receive(DatagramPacket p)从此套接字接收数据报包。当此方法返回时,DatagramPacket 的缓冲区填充了接收的数据。数据报包也包含发送方的 IP 地址和发送方机器上的端口号。 此方法 在接收到数据报前一直阻塞。数据报包对象的 length 字段包含所接收信息的长度。如果信息比包的 长度长,该信息将被截短。 
 public InetAddress getLocalAddress()获取套接字绑定的本地地址。  public int getLocalPort()返回此套接字绑定的本地主机上的端口号。 
 public InetAddress getInetAddress()返回此套接字连接的地址。如果套接字未连接,则返回null。 
 public int getPort()返回此套接字的端口。如果套接字未连接,则返回-1。

 public DatagramPacket(byte[] buf,int length)构造 DatagramPacket,用来接收长 度为 length 的数据包。 length 参数必须小于等于 buf.length。

 public DatagramPacket(byte[] buf,int length,InetAddress address,int port)构造数 据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。length 参数必须小于等于 buf.length。

 public InetAddress getAddress()返回某台机器的 IP 地址,此数据报将要发往该 机器或者是从该机器接收到的。

 public int getPort()返回某台远程主机的端口号,此数据报将要发往该主机或 者是从该主机接收到的。

 public byte[] getData()返回数据缓冲区。接收到的或将要发送的数据从缓冲区 中的偏移量 offset 处开始,持续 length 长度。

 public int getLength()返回将要发送或接收到的数据的长度。

UDP网络通信

 流 程: 
  1. DatagramSocket与DatagramPacket
  2. 建立发送端,接收端
  3. 建立数据包
  4. 调用Socket的发送、接收方法
  5. 关闭Socket
 发送端与接收端是两个独立的运行程序

udp通信

    @Test
    public void UdpTestOneClient(){
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            byte [] data = "我是要传递的客户端".getBytes();
            InetAddress ia = InetAddress.getLocalHost();
            DatagramPacket packet = new DatagramPacket(data,0,data.length,ia,1001);
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket != null){
                socket.close();
            }
        }
    }

    @Test
    public void UdpTestOneServer(){
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(1001);
            byte [] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
            socket.receive(packet);
            System.out.println(new String(packet.getData(),0,packet.getLength()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

URL类 

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

它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何locate 这个资源。 

通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www,ftp 站点。浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。

 URL的基本结构由5部分组成: 
    <传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表 
    例如: http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123 
    #片段名:即锚点,例如看小说,直接定位到章节 
    参数列表格式:参数名=参数值&参数名=参数值....

 

URL类构造器

为了表示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"); 
     URL类的构造器都声明抛出非运行时异常,必须要对这一异常进行处理,通 常是用 try-catch 语句进行捕获。

URL类常用方法

一个URL对象生成后,其属性是不能被改变的,但可以通过它给定的 方法来获取这些属性: 
    public String getProtocol(  )     获取该URL的协议名 
    public String getHost(  )        获取该URL的主机名 
    public String getPort(  )        获取该URL的端口号 
    public String getPath(  )        获取该URL的文件路径 
    public String getFile(  )         获取该URL的文件名 
    public String getQuery(   )      获取该URL的查询名
            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

//            public String getProtocol(  )     获取该URL的协议名
            System.out.println(url.getProtocol());
//            public String getHost(  )           获取该URL的主机名
            System.out.println(url.getHost());
//            public String getPort(  )            获取该URL的端口号
            System.out.println(url.getPort());
//            public String getPath(  )           获取该URL的文件路径
            System.out.println(url.getPath());
//            public String getFile(  )             获取该URL的文件名
            System.out.println(url.getFile());
//            public String getQuery(   )        获取该URL的查询名
            System.out.println(url.getQuery());

URLConnection类

URL的方法 openStream():能从网络上读取数据
若希望输出数据,例如向服务器端的 CGI (公共网关接口-Common Gateway Interface-的简称,是用户浏览器和服务器端的应用程序进行连接的接口)程序发送一 些数据,
  则必须先与URL建立连接,然后才能对其进行读写,此时需要使用 URLConnection 。 URLConnection:表示到URL所引用的远程对象的连接。当与一个URL建立连接时, 首先要在一个 URL 对象上通过方法 openConnection() 生成对应的 URLConnection 对象。如果连接过程失败,将产生IOException. URL netchinaren
= new URL ("http://www.atguigu.com/index.shtml"); URLConnectonn u = netchinaren.openConnection( );

Summarize

位于网络中的计算机具有唯一的IP地址,这样不同的主机可以互相区分。 
客户端-服务器是一种最常见的网络应用程序模型。服务器是一个为其客户端提供某种特定 服务的硬件或软件。
  客户机是一个用户应用程序,用于访问某台服务器提供的服务。端口号 是对一个服务的访问场所,它用于区分同一物理计算机上的多个服务。
  套接字用于连接客户 端和服务器,客户端和服务器之间的每个通信会话使用一个不同的套接字。TCP协议用于实 现面向连接的会话。
Java 中有关网络方面的功能都定义在 java.net 程序包中。Java 用 InetAddress 对象表示 IP 地址,该对象里有两个字段:主机名(String) 和 IP 地址(int)。
类 Socket 和 ServerSocket 实现了基于TCP协议的客户端-服务器程序。Socket是客户端 和服务器之间的一个连接,连接创建的细节被隐藏了。
  这个连接提供了一个安全的数据传输 通道,这是因为 TCP 协议可以解决数据在传送过程中的丢失、损坏、重复、乱序以及网络 拥挤等问题,它保证数据可靠的传送。
类 URL 和 URLConnection 提供了最高级网络应用。URL 的网络资源的位置来同一表示 Internet 上各种网络资源。通过URL对象可以创建当前应用程序和 URL 表示的网络资源之 间的连接,
  这样当前程序就可以读取网络资源数据,或者把自己的数据传送到网络上去。

原文地址:https://www.cnblogs.com/zhaoyunlong/p/13178135.html