java socket传文件,客户端将文件读取到byte[]中,然后用Map对相关内容进行包装之后输出到服务器端,但服务器端读取文件内容的循环除第一次读取的Map是客户端写入过来的内容外,从第二次循环开始Map的内容都跟第一次一样的,请问怎么回事?
服务器端代码:
`public void run() {
ObjectInputStream is = null;
OutputStream os = null;
byte cache[] = new byte[1024];
Map map = null;
int len = 0;
String fileName = null;
int i = 0;
try {
is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
map = (Map)is.readObject();
fileName = "d:/" +(String)map.get("fn");
os = new BufferedOutputStream(new FileOutputStream(fileName));
//文件内容接收
while(true){
//map在第二次通过readObject方法读出后内容与第一次读取的值一样
map = (Map)is.readObject();
if(null==map){
continue;
}
if(((Boolean)map.get("fe"))){
break;
}
cache = (byte[])map.get("c");
if(null==cache || 0==cache.length){
continue;
}
len = (Integer)map.get("l");
os.write(cache,0,len);
map = null;
cache = null;
}
os.flush();
System.out.println("--->over");
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(null!=is){
is.close();
is = null;
}
if(null!=os){
os.close();
os = null;
}
if(null!=socket){
socket.close();
socket = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
客户端代码:
`public void actionPerformed(ActionEvent e) {
Map map = null;
Socket socket = null;
ObjectOutputStream oos = null;
InputStream is = null;
byte cache[] = new byte[1024];
int len = 0;
try {
socket = new Socket("192.168.88.154",8888);
socket.setSoTimeout(10*1000);
socket.setKeepAlive(true);
File file = new File(jTextField.getText());
is = new BufferedInputStream(new FileInputStream(file));
oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
//文件名称
map = new HashMap();
map.put("fn",file.getName());
map.put("fl",file.length());
map.put("fe",false);
oos.writeObject(map);
oos.flush();
//文件内容
while(true){
map.clear();
if((len=is.read(cache))<=0){
break;
}
map.put("c",cache);
map.put("l", len);
map.put("fe", false);
oos.writeObject(map);
}
oos.flush();
//文件结束
map = new HashMap();
map.put("fe",true);
oos.writeObject(map);
oos.flush();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try{
if(null!=is){
is.close();
is = null;
}
if(null!=oos){
oos.close();
oos = null;
}
if(null!=socket){
socket.close();
socket = null;
}
}catch (Exception e1){
e1.printStackTrace();
}
}
}