三个类文件
常量类 Comm.java
package dwn;
public class Comm {
public static final String IP = "127.0.0.1";
public static final int PORT = 8888;
public static final String DOWNFILE = "aa.wma"; // 下载建立的新文件
public static final String SOURCEFILE = "a.wma";// 目标源文件
public static final int SPEED = 128;
}
服务器类 Server.java (包含Process类)
package dwn;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
/**
* @param args
*/
public static void main(String[] args) {
try {
System.out.println("Socket服务器正在运行...");
ServerSocket ss = new ServerSocket(Comm.PORT);
while (true) {
new Thread(new Process(ss.accept())).run();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Process implements Runnable {
Socket skt = null;
Process(Socket s) {
skt = s;
}
public void run() {
FileInputStream fis = null;
byte[] buf = new byte[Comm.SPEED];
int len = 0;
try {
len = skt.getInputStream().read(buf);
File file = new File(new String(buf, 0, len));
fis = new FileInputStream(file);
while (fis.read(buf) != -1) {
System.out.println("read file...");
skt.getOutputStream().write(buf);
}
skt.close();
fis.close();
buf = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户类 Client.java
package dwn;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
File file = new File(Comm.DOWNFILE);
FileOutputStream fos = null;
try {
file.createNewFile();
fos = new FileOutputStream(file);
Socket s = new Socket(Comm.IP, Comm.PORT);
byte[] buf = new byte[Comm.SPEED];
s.getOutputStream().write(Comm.SOURCEFILE.getBytes());
while (s.getInputStream().read(buf) != -1) {
System.out.println("write file...");
fos.write(buf);
}
fos.close();
s.close();
buf = null;
System.out.println("ok");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}