做了一個最簡單的,不過自己感覺包含好多東西
Server端:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public static void main(String[] args) throws IOException {
boolean isStop = false;
ServerSocket ss = null;
try {
ss = new ServerSocket(30000);
while (!isStop) {
Socket socket = ss.accept();
PrintStream ps1 = new PrintStream(socket.getOutputStream());
ps1.println("ok");
ps1.flush();
InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
String head = dis.readUTF();
Long length = dis.readLong();
System.out.println(head);
System.out.println(length);
File file = new File("d:\\a\\1234567.txt");
if (!file.exists()) {
file.createNewFile();
}
try {
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024 * 8];
int len = -1;
Long n = 0l;
while ((len = dis.read(buffer)) != -1) {
out.write(buffer, 0, len);
n += len;
if ((n + 1024 * 8) > length) {
int lastLen = (int) (length - n);
len = dis.read(buffer, 0, lastLen);
out.write(buffer, 0, len);
break;
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
String anotherhead = dis.readUTF();
System.out.println(anotherhead);
try {
if (in != null)
in.close();
} catch (Exception e) {
}
socket.close();
}
} catch (Exception e) {
}
}
}
Client端:
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 30000);
String flag = "";
Scanner scan = new Scanner(s.getInputStream());
if (scan.hasNextLine()) {
flag = scan.nextLine().trim();
}
if ("ok".equals(flag)) {
File file = new File("d:\\a\\a.txt");
if (!file.exists() || !file.isFile()) {
System.out.println("File \"" + args[2]
+ "\" does not exist or is not a normal file.");
System.exit(0);
}
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.writeUTF("aaaaaaaaaaaaaa");
out.writeLong(file.length());
FileInputStream in = null;
try {
in = new FileInputStream(file);
byte[] buffer = new byte[1024 * 8];
int len = -1;
System.out.println("File tansfer statr...");
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
System.out.println("File tansfer complete...");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
System.exit(1);
} finally {
try {
if (in != null)
in.close();
} catch (Exception e) {
}
}
out.writeUTF("bbbbbbbbbb");
if (out != null)
out.close();
}
if (scan != null)
scan.close();
if (s != null)
s.close();
}
}