网络编程(1)—TCP

java.net 包中提供了两种常见的网络协议的支持:

TCP:TCP 是传输控制协议的缩写,它保障了两个应用程序之间的可靠通信。通常用于互联网协议,被称 TCP / IP。

  1. TCP协议:

    • 使用TCP协议前需要建立TCP链接形成数据传输通道
    • 传输前采用三次握手方式,是可靠的
    • TCP协议进行通信的两个应用进程:客户端、服务端
    • 在连接中可进行大数据量的传输
    • 传输完毕,释放链接,效率低
  2. Socket编程
    • 通信的两端都要有Socket
    • 网络通信其实就是Socket之间通信
    • Socket允许程序把网络链接当成一个流,数据在两个Socket间通过IO传输
    • 发起请求的一端叫客户端,等待请求的一端为服务端
      *网络编程基本步骤:
  3. TCP网络编程步骤:

    • 1.创建客户端Socket
    • 2.Socket调用getOutputStream()方法,创建输出流(输入流)
    • 3.调用write()方法,写入数据
    • 4.接受来自服务端的信息
      *(若信息是双向传递的,即信息-来-回,而非单向传递,则需要在发送信息之后加上socket.shutdownOutput(),表示信息已发送完毕)
    • ———————————————
    • 5.创建服务端ServerSocket
    • 6.ServerSocket调用accept()方法,获取socket
    • 7.Socket调用getInputStream(),获取输入流
    • 8.接受来自客户端的信息
    • 9.处理来自客户端是信息
    • 10.返回信息给客户端
    • 11.关闭连接资源

TCP编程实例:

1.实例一:

客户端给服务端发送消息,服务端把消息输出到控制台上(单向发送消息)
//信息单向传递
//客户端—发送消息
//服务端—接收消息

public class TestTCP {

    //客户端
    @Test
    public void client(){

        Socket socket = null;//初始化时要置空,否则在finally语句中,关闭连接时会报错

        OutputStream os = null;
        try {
            //1.首先创建Socket,通过构造器指明服务端的IP地址以及接受程序的端口号
            socket = new Socket(InetAddress.getByName("localhost"), 9090);
            //2.Socket调用getOutputStream,创建流,发送数据
            os = socket.getOutputStream();
            //3.通过流,发送信息
            os.write("我是客户端!".getBytes());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(os != null){
                //4.关闭链接
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }               
            }
            if(socket != null){
                //5.关闭Socket链接
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //服务端
    @Test
    public void server(){

        ServerSocket ss = null;

        Socket s = null;

        InputStream is = null;
        try {
            //1.创建ServerSocket对象,通过构造器指明自身的端口号
            ss = new ServerSocket(9090);
            //2.调用accept(),返回一个Socket对象
            s = ss.accept();
            //3.调用Socket对象的getInputStream()获取一个从客户端发送过来的输入流
            is = s.getInputStream();
            //4.从流中读取数据,存到Byte[]数组中
            byte[] b = new byte[20];
            int len;
            while((len = is.read(b)) != -1){
                //先用String str接收
                String str = new String(b, 0, len);
                System.out.print(str);
                System.out.println("收到来自"+s.getInetAddress().getHostName()+"的信息");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }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();
                }
            }
        }
    }

}

2.实例二:

  • 客户端给服务端发送消息,服务端将消息打印到控制台上,同时发送“已收到信息”给客户端(一来一回消息传递)
    *信息双向发送
    *客户端:发送信息–接受信息
    *客户端(信息发送完毕之后要显示的告诉服务端,发送完毕!)
    *服务端:接受信息–发送信息

代码:

public class TestTCP1 {

    //客户端
    @Test
    public void client(){
        //1.创建Socket对象
        Socket socket = null;
        //2.输出流
        OutputStream os = null;
        //接收来自服务器的响应信息,输入流
        InputStream is = null;
        try {
            //socket = new Socket(InetAddress.getLocalHost(), 8989);作用同下一样
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 8989);
            os = socket.getOutputStream();
            //发送信息,到服务器,写信息
            String st = new Scanner(System.in).nextLine();
            os.write(st.getBytes("GBK"));
            socket.shutdownOutput();//输出完毕
            is = socket.getInputStream();
            int len;
            byte[] b = new byte[20];
            //接收信息,来自服务器的信息
            System.out.print("客户端:已发送!
");
            while((len = is.read(b)) != -1){
                String str = new String(b,0,len,"GBK");
                System.out.print(str);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }               
            }
            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(){
        //1.ServerSocket对象
        ServerSocket ss = null;
        Socket s = null;
        //2。输入流对象
        InputStream is = null;
        //服务器响应,返回发送信息
        OutputStream os = null;
        try {
            ss = new ServerSocket(8989);
            s = ss.accept();
            is = s.getInputStream();
            byte[] b = new byte[20];
            int len;
            //接收客户端发送的消息
            //System.out.print("");
            while((len = is.read(b)) != -1){
                String str = new String(b,0,len,"GBK");
                System.out.print(str);
            }
            //发送信息
            os = s.getOutputStream();
            os.write("服务端已收到消息,啦啦啦啦啦啦啦!".getBytes("GBK"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(os != null){
                try {
                    os.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();
                }
            }
        }
    }
}

3.实例三:

  • 从客户端发送文件到服务端,服务端保存到本地,并返回“发送成功!”给客户端,关闭相关链接
  • 客户端:首先读文件进来到程序(入)—发送文件(出)—接受返回信息(入)
  • 服务端:接受文件(入)—程序写出文件保存本地(出)—返回信息(出)

代码:

public class TestTCP2 {

    //客户端
    @Test
    public void client(){
        //1.创建Socket对象
        Socket socket = null;    
        //2.创建文件对象,创建输入流对象(文件首先要加读入到程序中)
        FileInputStream fis = null;
        //3.输出流,进行文件传输
        OutputStream os = null;
        //6.接受发送成功后返回信息
        InputStream is1 = null;
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"),9898);
            os = socket.getOutputStream();  
            fis = new FileInputStream(new File("file/1.jpg"));
            //5.传输文件,文件首先要读入到程序(len = is.read(b)),再写出(os.write(b, 0, len);)
            byte[] b = new byte[1024];
            int len;
            //文件读入到程序,并进行传输
            while((len = fis.read(b)) != -1){
                os.write(b, 0, len);
            }
            //6.发送完毕
            socket.shutdownOutput();
            //7.接收返回的信息
            is1 = socket.getInputStream();
            byte[] b1 = new byte[20];
            int leng;
            while((leng = is1.read(b1)) != -1){
                String str = new String(b1, 0, leng);
                System.out.println(str);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(is1 != null){
                try {
                    is1.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(){
        //1.服务端ServerSocket
        ServerSocket ss = null;
        //2.调用accept()方法,返回一个Socket对象
        Socket s = null;
        //3.接受数据
        InputStream is = null;
        //4.创建文件对象,用于承载数据
        FileOutputStream fos = null;
        //6.返回信息
        OutputStream os1 = null;
        try {
            ss = new ServerSocket(9898);
            s = ss.accept();
            is = s.getInputStream();
            fos = new  FileOutputStream(new File("file/1_1.jpg"));
            //5.接收数据(len = is.read()),写出文件(os.write())
            byte[] b = new byte[1024];
            int len;
            while((len = is.read(b)) != -1){
                fos.write(b , 0 , len);
            }
            os1 = s.getOutputStream();
            os1.write("发送成功!".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(os1 != null){
                try {
                    os1.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();
                }
            }
        }
    }

}