java TCP通信 socket 套接字 用图片上传轰炸服务器

客户端

package com.swift.jinji;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/*项目需求:使用socket编写一个Java程序,要求:实现客户端上传文件到服务端,
即客户端读取本地文本文件,将文件发送至服务端,服务端将接收到的内容存放到文本文件中。*/

public class UploadClient {

    static int i = 1024;

    public static void main(String[] args) throws IOException, IOException {

        while (true) {
            if (i < 65535) {
                System.out.println(i);
                Socket s = new Socket("192.168.122.35", 20000);
                FileInputStream fis = new FileInputStream("d:/abc/0.jpg");
                OutputStream out = s.getOutputStream();
                byte[] buf = new byte[1024];
                int len;
                while ((len = fis.read(buf)) != -1) {
                    // 这个时候下面的套接字流write写没有写-1,因为到-1就停了
                    out.write(buf, 0, len);
                }
                s.shutdownOutput();
                InputStream in = s.getInputStream();
                len = in.read(buf);
                System.out.println(new String(buf, 0, len));
            }
        }
    }

}

服务器端需开启上传接收客户端socket才行

package com.swift.jinji;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadServer {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(20000);
        while (true) {
            System.out.println("等待客户端连接");
            Socket s = serverSocket.accept();
            System.out.println("有客户端连接成功 " + s);
            byte[] buf = new byte[1024];
            int len;
            File destDir = new File("d:/upload");
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(new File(destDir, System.currentTimeMillis() + "_0.jpg"));
            InputStream in = s.getInputStream();
            while ((len = in.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            System.out.println("111111111111111");
            OutputStream out = s.getOutputStream();
            out.write("上传成功".getBytes());
            s.close();
        }
    }

}

效果就是,一瞬间会有数万张图片奔向服务器.

posted @ 2018-03-11 18:44  Advancing-Swift  阅读(701)  评论(0编辑  收藏  举报