// 从服务器端获取封面图片
public  synchronized void loadImage(Socket s) {
InputStream is = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
is = s.getInputStream();
bis = new BufferedInputStream(is);
byte[] b1 = new byte[4];
bis.read(b1);
int num = b2i(b1);
System.out.println("从服务器读取歌手图片数量:" + num);
for (int i = 0; i < num; i++) {
byte[] b2 = new byte[4];
bis.read(b2);
//名字长度
int name_len = b2i(b2);
System.out.println("图片名字长度:" + name_len);
byte[] name1 = new byte[name_len];
bis.read(name1);
String img_name = new String(name1);
System.out.println("从服务器端读取图片名:" + img_name);
//开始保存到客户端文件夹
File file = new File("res/image/" + img_name);
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
byte[] b3 = new byte[4];
bis.read(b3);
int img_size = b2i(b3);
System.out.println("客户端:" + img_name + "大小:" + img_size);
// 开始保存到文件
int count = 0;
byte[] buffer = new byte[1024];
while (count < img_size) {
int c = bis.read(buffer);
bos.write(buffer, 0, c);
count = count + c;
}
bos.flush();
}
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
} }
javaswingiosocketnet

解决方案 »

  1.   

    上面是接收,这里是发送
    // 发送推荐歌手图片到客户端程序
    private synchronized void sendImage(Socket s) {
    File file = null;
    FileInputStream fis = null;
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    try {
    file = new File("config/recommend/image");
    String[] img = file.list();
    // 图片数量
    int num = img.length;
    System.out.println("服务器端歌手图片数量:" + num);
    OutputStream os = s.getOutputStream();
    bos = new BufferedOutputStream(os);
    // 转换为byte数组发送到客户端
    bos.write(i2b(num));
    bos.flush();
    // 发送图片
    for (int i = 0; i < img.length; i++) {
    // 发送专辑图片名长度以及图片名
    String name = img[i];
    byte[] bName = name.getBytes();
    int name_len = bName.length;
    // 图片名长度
    bos.write(i2b(name_len));
    // 图片名
    bos.write(bName);
    // 发送图片内容长度
    File image = new File(file.getAbsolutePath() + "/" + name);
    int img_size = (int) image.length();
    bos.write(i2b(img_size));
    bos.flush();
    // 开始发送图片内容
    fis = new FileInputStream(image);
    bis = new BufferedInputStream(fis);
    // 边读边写
    byte[] buffer = new byte[1024];
    int count = -1;
    while ((count = bis.read(buffer)) != -1) {
    bos.write(buffer, 0, count);
    }
    bos.flush();
    }
    bis.close();
    fis.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(0);
    }
    }