用Socket传输文件的问题 (很多分,想要吗?)
//Server.java
package test;
import java.net.*;
import java.io.*;
import java.util.zip.*;
import java.util.*;
public class Server {
static int PORT = 9999;
public static void main(String[] args) throws IOException {
//Server server1 = new Server();
if(args.length != 1){
System.out.println("Usage:java Server file.name");
System.exit(1);
}
File inFile = new File(args[0]);
if(inFile.canRead() != true){
System.out.println("Can't read File:" + args[0]);
System.exit(1);
}
BufferedInputStream in = new BufferedInputStream(new FileInputStream(inFile));
ServerSocket server = new ServerSocket(Server.PORT);
System.out.println("Waiting connection ...");
Socket socket = server.accept();
System.out.println("Socket connected in");
BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(socket.getOutputStream()),4096);
System.out.println("Writing ...");
System.out.println(new Date());
byte[] c = new byte[4096];
while ((in.read(c)) != -1) {
out.write(c);
}
System.out.println("Writing done!");
System.out.println(new Date());
in.close();
out.close();
socket.close();
System.out.println("Socket closed.");
}
}
//Client.java
package test;
import java.net.*;
import java.io.*;
import java.util.zip.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws IOException{
//Client client1 = new Client();
if(args.length != 1){
System.out.println("Usage:java Client hostName");
System.exit(1);
}
File outFile = new File("out");
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
Socket client = new Socket(args[0], Server.PORT);
System.out.println("Connect ...");
System.out.println(new Date());
BufferedInputStream in = new BufferedInputStream(new GZIPInputStream(client.getInputStream()),4096);
System.out.println("Reading ...");
byte[] c = new byte[4096];
while ((in.read(c)) != -1) {
out.write(c);
}
System.out.println("Reading down.");
System.out.println(new Date());
in.close();
out.close();
client.close();
System.out.println("Closed.");
}
}
//---------------------------------------------------------------
传163M的文件用了204秒,文件没错误,可以使用
传1k的就坏了,文件变大了,知道原因,但不知道怎么解决