我用Socket发送图片时会报这个错误发送方:try{intsize=2*1024;byte[]buffer=newbyte[size];byte[]b=null;intlen;for(inti=0;i
我用Socket发送图片时会报这个错误
发送方:
try{
int size=2*1024;
byte[] buffer=new byte[size];
byte[] b=null;
int len;
for(int i=0;i
for(int j=0;j
File file=new File("D:\\"+level+"\\"+i+"_"+j+".png");
FileInputStream inputStream=new FileInputStream(file);
len=-1;
dos.writeUTF(file.getName());
dos.writeLong(file.length());
while((len=inputStream.read(buffer))!=-1){
dos.write(buffer,0,len);
if(len!=size){
b=new byte[size-len];
dos.write(b,0,b.length);
}
}
inputStream.close();
}
}
dos.writeUTF("end");
}catch(Exception e){
e.printStackTrace();
}
接收方:
LinkedHashMap map=new LinkedHashMap();
try{
System.out.println("class_Receive socket "+socket);
while(true){
DataInputStream inputStream=new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte[] buffer = new byte[2 * 1024];
int len = -1;
String imageName = null;
long fileLength = -1;
while(true) {
imageName = inputStream.readUTF();
if(imageName != null && imageName.trim().equals("end")) {
break;
}
fileLength = inputStream.readLong();
len = -1;
ByteArrayOutputStream baos=new ByteArrayOutputStream();
while(fileLength > 0) {
len = inputStream.read(buffer);
baos.write(buffer,0,len);
if(len != -1) {
fileLength -= len;
}
}
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
BufferedImage image=ImageIO.read(bais);
map.put(imageName,image);
}
socket.close();
break;
}
}catch(IOException e){
e.printStackTrace();
}
什么原因
展开