随笔-网络编程实现TCP协议传输文件

客户端 需要注意的是,该代码偷懒,关闭资源操作,必须使用try-catch-finally,最好使用try-with-resources格式

public void client() {
    Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
    OutputStream os = socket.getOutputStream;
    BufferInputStream bis = new BufferInputStream(new FileInputStream("hello.txt"));
    
    byte[] buffer = new byte[1024];
    int len;

    while((len = bis.read(buffer)) != -1) {
        os.write(buffer, 0, len);
    }

    socket.shutdownOutput();

    InputStream is = new InputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
    while((len = is.read(buffer)) != -1) {
        baos.write(buffer, 0, len);
    }

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

    baos.close();
    is.close();
    bis.close();
    socket.close();
}

服务端

Socket accept = new ServerSocket(9090).accept();
        InputStream is = accept.getInputStream();

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("hello2.txt"));

        byte[] buffer = new byte[1024];
        int len;

        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }

        OutputStream ops = accept.getOutputStream();
        ops.write("接收成功".getBytes());

        ops.close();
        bos.close();
        is.close();
        accept.close();

 

posted @ 2021-01-24 17:04  ADF_CcXx  阅读(59)  评论(0)    收藏  举报