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();
    }

    }

    }

  • 相关阅读:
    hdu-2841 Visible Trees---容斥定理
    hdu-4135 Co-prime---容斥定理经典&&求1-m中与n互质的数目
    hdu-1796 How many integers can you find---容斥定理
    hdu-2837 Calculation---指数循环节
    FZU-1759 Super A^B mod C---欧拉降幂&指数循环节
    指数循环节&欧拉降幂
    hdu-3074 Multiply game---线段树+单点更新
    hdu-1792 A New Change Problem---数论&剩余系
    POJ-2429 GCD & LCM Inverse---给出gcd和lcm求原来两个数
    hdu-2685 I won't tell you this is about number theory---gcd和快速幂的性质
  • 原文地址:https://www.cnblogs.com/angel512/p/5868146.html
Copyright © 2011-2022 走看看