zoukankan      html  css  js  c++  java
  • 简单的传输文件范例

    package j2se.core.net.tcp.file;


    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;

    /**
    * 简单的传输文件范例(接受端)
    *
    */
    public class Server {

    public static void main(String[] args) throws IOException {
    // 在8888端口创建一个 ServerSocket
    ServerSocket server = new ServerSocket(8888);
    // 循环等待客户的连接
    while (true) {
    // 主线程会一直阻塞到客户连接的传入
    Socket socket;
    try {
    socket = server.accept();
    BufferedOutputStream output = new BufferedOutputStream(
    new FileOutputStream(
    new File(socket.getPort() + ".tmp")));
    byte[] data = new byte[1024];
    while (true) {

    int i = socket.getInputStream().read(data);
    if (i == -1)
    break;
    output.write(data, 0, i);
    }

    output.close();
    socket.close();
    } catch (IOException e) {
    e.printStackTrace();
    }

    }
    }

    }

    package j2se.core.net.tcp.file;


    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;

    /**
    * 简单的传输文件范例(发送端)
    *
    */
    public class Client {

    public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    String ip = "127.0.0.1";
    int port = 8888;

    System.out.println("请输入文件名:");
    String s = scan.nextLine();

    try {
    Socket socket = new Socket(ip, port);
    BufferedOutputStream output = new BufferedOutputStream(socket
    .getOutputStream());
    BufferedInputStream input = new BufferedInputStream(
    new FileInputStream(new File(s)));
    try {
    byte[] data = new byte[1024];
    while (true) {
    int i = input.read(data);
    if (i == -1)
    break;
    output.write(data, 0, i);
    }
    output.flush();
    } catch (Exception e) {
    // 由于服务器主动断连接,所以会出现异常
    } finally {
    output.close();
    input.close();
    socket.close();
    }
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    }

    }

  • 相关阅读:
    es6-compact-table 名词备忘
    JS 防抖和节流函数
    为什么 JS 对象内部属性遍历的顺序乱了
    JS 发送 HTTP 请求方法封装
    JS 一些位操作的妙用
    JS 格式化时间
    linux ssh连接
    c# checked 和 unchecked
    c# mvc action 跳转方式
    IIS 动态与静态压缩
  • 原文地址:https://www.cnblogs.com/angel512/p/5868146.html
Copyright © 2011-2022 走看看