关于我是小白这件事 2021-12-05 14:12 采纳率: 66.7%
浏览 19
已结题

客户端往服务端发送图片数据丢失

客户端往服务端发送图片,可以显示有.JPG,但是是0kb

public class Demo2 {

@Test
public void client() throws IOException
{
    Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),8898);
    OutputStream outputStream = socket.getOutputStream();
    BufferedInputStream bis  =
            new BufferedInputStream(new FileInputStream(new File("F:\\exer\\01.JPG")));

    byte[] buf = new byte[1024];
    int len;
    while((len = bis.read())!=-1)
    {
        outputStream.write(buf,0,len);
    }
    System.out.println("客户端发送成功");
    bis.close();
    outputStream.close();
    socket.close();

}

@Test
public void server() throws IOException {
    ServerSocket serverSocket = new ServerSocket(8898);
    Socket accept = serverSocket.accept();
    InputStream inputStream = accept.getInputStream();

    BufferedOutputStream bos =
            new BufferedOutputStream(new FileOutputStream(new File("F:\\exer\\TCP03.JPG")));
    byte[] buf = new byte[1024];
    int len;
    while((len = inputStream.read())!=-1)
    {
        bos.write(buf,0,len);
    }
    System.out.println("服务端接受成功");
    bos.close();
    inputStream.close();
    accept.close();
    serverSocket.close();
}

}
客户端运行结果:
客户端发送成功

Process finished with exit code 0

服务端运行结果:
服务端接受成功

Process finished with exit code 0

  • 写回答

1条回答 默认 最新

  • 关注
    
    while((len = bis.read())!=-1)
        {
            outputStream.write(buf,0,len);
        }
    改为
    while((len = bis.read(buf,0,buf.length))!=-1)
        {
            outputStream.write(buf,0,len);
        }
        outputStream.flush();
        outputStream.close();
    
    
    while((len = inputStream.read())!=-1)
        {
            bos.write(buf,0,len);
        }
    改为
    while((len = inputStream.read(buf,0,buf.length))!=-1)
        {
            bos.write(buf,0,len);
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 12月14日
  • 已采纳回答 12月6日
  • 创建了问题 12月5日

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵