Java网络编程

1. 网络编程概述

image.png

2. 网络通信的要素

网络编程的要素

  1. IP和端口号
  2. 网络通信协议:TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)
  • IP区分不同的设备
  • 端口号区分同一台设备上不同的应用

image.png

image.png

2.1 IP和端口号 (通信要素一)

2.1.1 IP (Inet Protocol)

  1. IP:唯一的标识 Internet 上的计算机(通信实体)
  2. 在Java中使用InetAddress类代表IP
  3. IP分类:
    • IPv4 和 IPv6
      • IPV4:使用4个字节,4个0-255的数字组成,大概42亿个,已用尽;
      • IPV6:128位,写成8个无符号整数,每个整数用4个十六进制表示,如:3ffe:3201:1401:1280:c8ff:fe4d:db39:1984
    • (公网地址)万维网 和 (私有地址)局域网
      • 192.168开头的就是私有地址,范围为192.168.0.0-192.168.255.255,专门为组织机构内部使用
  4. 域名: www.baidu.com www.sina.com www.jd.com
  5. 本地(本机)IP地址:127.0.0.1 对应着:localhost
  6. InetAddress中的常用方法
    • 如何实例化InetAddress:两个方法:getByName(String host) 、 getLocalHost() 返回InetAddreess对象
    • 两个常用方法:getHostName() / getHostAddress()
public static void main(String[] args) {

        try {
            //File file = new File("hello.txt");
            InetAddress inet1 = InetAddress.getByName("192.168.10.14");

            System.out.println(inet1);

            InetAddress inet2 = InetAddress.getByName("www.atguigu.com");
            System.out.println(inet2);

            InetAddress inet3 = InetAddress.getByName("127.0.0.1");
            System.out.println(inet3);

            //获取本地ip
            InetAddress inet4 = InetAddress.getLocalHost();
            System.out.println(inet4);

            //getHostName()
            System.out.println(inet2.getHostName());
            //getHostAddress()
            System.out.println(inet2.getHostAddress());

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

    }

2.1.2 端口号(port)

  1. 端口号标识正在计算机上运行的进程。不同的进程有不同的端口号

  2. 范围:一个 16 位的整数 0~65535。

  3. 端口分类

    • 公认端口:0~1023。被预先定义的服务通信占用(如:HTTP占用端口
      80,FTP占用端口21,Telnet占用端口23)
    • 注册端口:1024~49151。分配给用户进程或应用程序。(如:Tomcat占用端口8080,MySQL占用端口3306,Oracle占用端口1521等)。
    • 动态/私有端口:49152~65535。
  4. 端口号与IP地址的组合得出一个网络套接字:Socket

网络协议 (通信要素二)

  1. 计算机网络中实现通信必须有一些约定,即通信协议,对速率、传输代码、代码结构、传输控制步骤、出错控制等制定标准。
  2. 通信协议分层思想:在制定协议时,把复杂成份分解成一些简单的成份,再将它们复合起来。最常用的复合方式是层次方式,即同层间可以通信、上一层可以调用下一层,而与再下一层不发生关系。各层互不影响,利于系统的开发和扩展。
  3. TCP/IP协议簇
    • 传输层两个重要的协议:
      • TCP(传输控制协议):传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议
      • UDP(用户数据报协议)
    • IP协议是网络层的主要协议,支持网络互联的数据通信
    • TCP/IP协议模型从更实用的角度出发,形成了四层体系结构:物理链路层、IP层、传输层和应用层

image.png

TCP类似于打电话
UDP类似于发短信、发电报;比如看体育比赛视频使用UDP,允许丢失几帧画面,但是要保证速度快
image.png

建立连接:“三次握手”是为了保证点对点通信是可靠的
image.png

释放连接:“四次挥手
image.png

3. TCP网络编程

TCP(传输控制协议):传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议
例子1:客户端发送信息给服务端,服务端将数据显示在控制台上

3.1 什么是Socket(套接字)

-对网络中不同主机上的应用进程之间进行双向通信的端点的抽象,网络Socket是IP地址与端口的组合
-ocket是一个抽象层,应用程序可以通过它发送或接收数据,可对其进行像对文件一样的打开、读写和关闭等操作。套接字允许应用程序将I/O插入到网络中,并与网络中的其他应用程序进行通信。

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。 即不能通过此套接字的输出流发送任何数据

image.png

3.2 TCP编程例题一

客户端发送信息给服务端,服务端将数据显示在控制台上

 //* 实现TCP的网络编程 
    //客户端
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("192.168.14.100");
            socket = new Socket(inet, 8899);
            //2.获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3.写出数据的操作
            os.write("你好,我是客户端mm".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            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 socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号
            ss = new ServerSocket(8899);
            //2.调用accept()表示接收来自于客户端的socket
            socket = ss.accept();
            //3.获取输入流
            is = socket.getInputStream();

            //不建议这样写,可能会有乱码
//        byte[] buffer = new byte[1024];
//        int len;
//        while((len = is.read(buffer)) != -1){
//            String str = new String(buffer,0,len);
//            System.out.print(str);
//        }
            //4.读取输入流中的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

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

            System.out.println("收到了来自于:" + socket.getInetAddress().getHostAddress() + "的数据");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                //5.关闭资源
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

先运行服务器端,再运行客户端发送信息
然后服务器端(server)接收到信息
image.png

注意:

  1. 为了解决中文乱码的问题,输出流使用了ByteArrayOutputStream这个类
  2. 如何查看端口号:在命令行输入netstat,冒号后面的就是端口号
    image.png

3.3 TCP编程例题二

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

public class TCPTest2 {
    //客户端
    //这里涉及到的异常,应该使用try-catch-finally处理
    @Test
    public void client() throws IOException {
        //1.创建Socket对象,指明IP和端口号
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        //2.得到socket的输出流
        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);
        }
        //5.资源的关闭
        fis.close();
        os.close();
        socket.close();
    }

    //服务器端
    //这里涉及到的异常,应该使用try-catch-finally处理
    @Test
    public void server() throws IOException {
        //1.创建ServerSocket对象,指出自己的端口号
        ServerSocket ss = new ServerSocket(9090);
        //2.调用ServerSocket的accept方法,得到Socket
        Socket socket = ss.accept();
        //3.得到Socket的输入流
        InputStream is = socket.getInputStream();
        //4.创建文件输出流,准备将从Socket读到的数据写出到本地
        FileOutputStream fos = new FileOutputStream(new File("beauty1.jpg"));
        //5.
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        //6.关闭Socket和流资源
        fos.close();
        is.close();
        socket.close();
        ss.close();
    }
}

3.4 TCP编程例题三

从客户端发送文件给服务端.服务端保存到本地,并返回“发送成功”给客户端。最后关闭相应的连接。
注意

  1. 客户端图片传输完成之后,需要关闭服务器端Socket的输出流
public class TCPTest3 {

    /*
        这里涉及到的异常,应该使用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();
    }
}

客户端

  • 自定义
  • 浏览器

服务端

  • 自定义
  • Tomcat服务器

4. UDP网络编程

4.1 DatagramSocket和DatagramPacket

  1. DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序。
  2. UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证
    UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。
  3. DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP
    地址和端口号以及接收端的IP地址和端口号。
  4. 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。

DatagramPacket类的常用方法

  • 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()返回将要发送或接收到的数据的长度。

image.png

public class UDPTest {
    //发送端
    @Test
    public void sender() throws IOException {

        DatagramSocket socket = new DatagramSocket();

        String str = "我是UDP方式发送的导弹";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 9090);

        socket.send(packet);

        socket.close();

    }

    //接收端
    @Test
    public void receiver() throws IOException {

        DatagramSocket socket = new DatagramSocket(9090);

        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(packet);

        System.out.println(new String(packet.getData(), 0, packet.getLength()));

        socket.close();
    }
}

5. URL编程

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

URL的基本结构由5部分组成:
<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
例如: http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
image.png

URL类的构造器

image.png

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类下的常用方法

public static void main(String[] args) {
    try {
        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());

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

}

客户端从Tomcat服务器下载图片

public static void main(String[] args) {

        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("day10\\beauty3.jpg");

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }

            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

    }

两道TCP编程课后练习题

package exer;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

//1.TCP编程练习:服务端读取图片并发送给客户端,客户端保存图片到本地
public class TCPTest1 {
    @Test
    public void server() {
        ServerSocket serverSocket = null;
        Socket socket = null;
        OutputStream outputStream = null;
        FileInputStream fis = null;
        try {
            serverSocket = new ServerSocket(9090);
            socket = serverSocket.accept();
            outputStream = socket.getOutputStream();
            fis = new FileInputStream("linux.jpg");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            System.out.println("服务器已完成图片发送");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    //客户端
    @Test
    public void client() {
        Socket socket = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            InetAddress inet = InetAddress.getLocalHost();
            socket = new Socket(inet, 9090);
            inputStream = socket.getInputStream();
            fileOutputStream = new FileOutputStream("new_linux.jpg");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
            System.out.println("客户端已完成图片接收。");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null)
                    fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
package exer;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

//客户端给服务端发送文本,服务端会将文本转成大写在返回给客户端。
public class TCPTest2 {

    @Test
    public void client() {
        Socket socket = null;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        InputStream socketInputStream = null;
        InputStreamReader reader = null;
        FileWriter writer = null;
        try {
            socket = new Socket(InetAddress.getLocalHost(), 9091);
            outputStream = socket.getOutputStream();
            fileInputStream = new FileInputStream("hello.txt");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            System.out.println("客户端:已发送文本。");

            //客户端关闭输出,这样服务器不会一直接收
            socket.shutdownOutput();

            socketInputStream = socket.getInputStream();
            reader = new InputStreamReader(socketInputStream);
            writer = new FileWriter("new_hello.txt");
            char[] cbuffer = new char[1024];
            int len2;
            while ((len2 = reader.read(cbuffer)) != -1) {
                writer.write(cbuffer, 0, len2);
            }
            System.out.println("客户端:已接收到字符串,并写入新文件中。");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    @Test
    public void server() {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream socketInputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        OutputStream socketOutputStream = null;
        try {
            serverSocket = new ServerSocket(9091);
            socket = serverSocket.accept();
            socketInputStream = socket.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = socketInputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            String str = byteArrayOutputStream.toString();
            String upperCaseStr = str.toUpperCase();
            System.out.println("服务器:大写的字符串如下:" + upperCaseStr);

            socketOutputStream = socket.getOutputStream();
            socketOutputStream.write(upperCaseStr.getBytes());  //将字符串转化为byte数组

            System.out.println("服务器:已完成发送。");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socketInputStream != null)
                    socketInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socketOutputStream != null)
                    socketOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (serverSocket != null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (byteArrayOutputStream != null)
                    byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

注意:

  1. ByteArrayOutputStream的使用要注意:ByteArrayOutputSream内部有缓冲区,将使用buffer依次读入,最后调用ByteArrayOutputSream的toString方法可以得到完整的字符串。
  2. 练习二中将从socket得到的InputStream对象用InputStreamReader转化成Reader类型的对象,从而实现文本的读取操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值