多线程TCP文件上传
学习案例
Client.java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 客户端
* Created by Aongi on 2017/5/4.
* Version 1.0
*/
public class Client {
//main方法
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",8888);
//发送数据给服务器端
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream("d:\\df.jpg");
byte[] bytes = new byte[1024];
int i=0;
while ((i=fis.read(bytes))!=-1){
os.write(bytes,0,i);
}
//给服务器写终止序列
socket.shutdownOutput();
//接受服务器端返回的数据
InputStream is = socket.getInputStream();
i = is.read(bytes);
System.out.println(new String(bytes,0,i));
fis.close();
//关闭socket对象
socket.close();
}
}
Server.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Aongi on 2017/5/4.
* Version 1.0
*/
public class Server {
//main方法
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
while (true) {
// 获取到一个客户端,必须开启新线程,为这个客户端服务
Socket socket = server.accept();
new Thread(new TCPRunnable(socket)).start();
}
}
}
TCPRunnable.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Random;
/**
* Created by Aongi on 2017/5/4.
* Version 1.0
*/
public class TCPRunnable implements Runnable{
private Socket socket;
public TCPRunnable(Socket socket){
this.socket=socket;
}
@Override
public void run() {
try {
//通过客户端连接对象,获取字节输入流,读取客户端图片
InputStream in = socket.getInputStream();
//将目的文件夹封装到File对象
File upload = new File("E:\\tup");
if (!upload.exists())
upload.mkdirs();
//防止文件同名被覆盖,从新定义文件名字
//规则: 域名+毫秒值+6位随机数
String filename = "df" + System.currentTimeMillis() + new Random().nextInt(999999) + ".jpg";
//创建字节输出流,将图片写入到目的文件夹中
FileOutputStream fos = new FileOutputStream(upload + File.separator + filename);
//读写字节数组
byte[] bytes = new byte[1024];
int len = 0;
while ((len = in.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
//通过客户端连接对象获取字节输出流
//上传成功写回客户端
socket.getOutputStream().write("上传成功".getBytes());
fos.close();
socket.close();
}catch (IOException e){
throw new RuntimeException("文件上传失败!");
}
}
}