如何在Java Socket服务器中发送图像到浏览器,确保不会损坏?

huangapple 未分类评论53阅读模式
英文:

How can I send an image from java socket Server to a navigator wihtout being corrupted?

问题

  1. 我正在尝试编写一个Java套接字服务器从该服务器将图像发送到导航器客户端)。但是当我发送图像时文件似乎损坏显示带有符号的图像)。
  2. DataOutputStream dout = new DataOutputStream(connectS.getOutputStream());
  3. String file = "image.jpg";
  4. File filename = new File(file);
  5. FileInputStream fin = new FileInputStream(filename);
  6. // dout.writeUTF(file);
  7. System.out.println("正在发送图像...");
  8. int size = (int) filename.length();
  9. byte[] readData = new byte[size];
  10. fin.read(readData);
  11. dout.writeInt(size);
  12. dout.flush();
  13. dout.write(readData, 0, size);
  14. /*for(int i=0;i<readData.length;i++) {
  15. dout.write(readData, 0, i);
  16. }*/
  17. dout.flush();
  18. 这是我启动程序的方式
  19. ServerSocket ss = new ServerSocket(8080);
  20. Socket connectS = ss.accept();
  21. BufferedReader in = new BufferedReader(new InputStreamReader(connectS.getInputStream()));
  22. 感谢您的帮助
英文:

I am trying to code a java socket server to send an image from this server to the navigator(client side). But when I send the image the file seen to be corrupted (display the image with symbols).

  1. DataOutputStream dout = new DataOutputStream(connectS.getOutputStream());
  2. String file=&quot;image.jpg&quot;;
  3. File filename = new File(file);
  4. FileInputStream fin = new FileInputStream(filename);
  5. //dout.writeUTF(file);
  6. System.out.println(&quot;Sending image...&quot;);
  7. int size=(int) filename.length();
  8. byte[] readData = new byte[size];
  9. fin.read(readData);
  10. dout.writeInt(size);
  11. dout.flush();
  12. dout.write(readData,0,size);
  13. /*for(int i=0;i&lt;readData.length;i++) {
  14. dout.write(readData, 0, i);
  15. }*/
  16. dout.flush();

Here is how I start the program

  1. ServerSocket ss=new ServerSocket(8080);
  2. Socket connectS=ss.accept();
  3. BufferedReader in=new BufferedReader(new InputStreamReader(connectS.getInputStream()));

Thanks for your help!!!

答案1

得分: -1

我解决了这个问题。
首先,删除dout.readInt();
然后,打开Microsoft Edge;(Mozilla显示图像,但似乎存在编码问题,这是我的观点,可能不是真正的原因);

英文:

I solved the problem.
First, remove dout.readInt();
Then, open microsoft edge;(mozilla shows the image but there seems to be an encoding issue,that's my opinion,maybe not the true);

huangapple
  • 本文由 发表于 2020年4月8日 17:48:07
  • 转载请务必保留本文链接:https://java.coder-hub.com/61097829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定