果然上机暴露的问题就是多。
今天复习到写TCP并发上传图片,但是复制出来的图片就是有一片灰色,复制不到。
浪费了半个下午加一晚上,又看书又看Buffered流的源码又上机逐行代码试,
最后实在不行去问别人,原来是因为flush()方法。
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws UnknownHostException,
IOException {
ServerSocket ss = new ServerSocket(10003);
Socket s = ss.accept();
String IP = s.getInetAddress().getHostAddress();
int count = 1;
File file = new File("C:\\JavaFiles\\A\\" + IP + ".jpg");
while (file.exists()) {
file = new File("C:\\JavaFiles\\A\\" + IP + "_" + (count++)
+ ".jpg");
}
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(in);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buf = new byte[1024];
int len = 0;
int lenCount = 0;
while ((len = bis.read(buf)) != -1) {
System.out.println("A:" + len);// test
bos.write(buf, 0, len);
// bos.flush();
lenCount = lenCount + len;
System.out.println("B:" + lenCount);// test
}
System.out.println(lenCount);
}
}
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws UnknownHostException,
IOException {
if (args.length != 1) {
System.out.println("Please entry fileName.");
return;
}
File file = new File(args[0]);
if (!file.exists()) {
System.out.println("File is not existed.");
return;
}
if (!file.getName().endsWith(".jpg")) {
System.out.println("File is not a jpg file.");
return;
}
if (file.length() > 1024 * 1024) {
System.out.println("must more than 1M.");
return;
}
Socket s = new Socket(InetAddress.getByName("localhost"), 10003);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(out);
byte[] buf = new byte[1024];
int len = 0;
int lenCount = 0;
while ((len = bis.read(buf)) != -1) {
// bos.write(buf,0,len);
out.write(buf, 0, len);
lenCount = lenCount + len;
}
System.out.println(lenCount);
s.shutdownOutput();
fis.close();
bis.close();
bos.close();
// s.close();
}
}
如果缓冲区操作最后那部分没有存满,既不flush()最后又不close()就会发生这种情况。