客户端:
package cn.sasa.socketUploadFileDemo; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket; public class SocketClientDemo { public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",8050);
OutputStream output = socket.getOutputStream(); FileInputStream inputFile = new FileInputStream("D:\\sasa\\Weixin.zip");
byte[] buff = new byte[1024];
int len = 0;
while((len = inputFile.read(buff)) != -1) {
output.write(buff,0,len);
}
//传完后告诉服务器上传完成,否则服务器会一直等待读取
socket.shutdownOutput(); InputStream input = socket.getInputStream();
len = input.read(buff);
System.out.println(new String(buff,0,len)); socket.close();
inputFile.close();
}
}
服务端:
package cn.sasa.socketUploadFileDemo; import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; public class ServerSocketDemo { public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8050);
//一直监听
while(true) {
Socket clientSocket = server.accept();
Thread th = new Thread(new UploadRunnable(clientSocket));
th.start();
}
} }
Runnable接口的实现类UploadRunnable.java,用于上传文件
package cn.sasa.socketUploadFileDemo; import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket; public class UploadRunnable implements Runnable { private Socket clientSocket;
public UploadRunnable(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
InputStream input = clientSocket.getInputStream();
File upload = new File("D:\\upload");
if(!upload.exists()) {
upload.mkdirs();
}
//文件命名
String fileName = "sasa"+ System.currentTimeMillis()+".zip";
FileOutputStream outputFile = new FileOutputStream(upload+File.separator+fileName);
byte[] buff = new byte[1024];
int len = 0;
while((len = input.read(buff)) != -1) {
outputFile.write(buff,0,len);
}
OutputStream output = clientSocket.getOutputStream();
output.write("上传完成".getBytes());
outputFile.close();
clientSocket.close();
}catch(Exception ex) {
ex.printStackTrace();
}
} }