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

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

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

问题

我正在尝试编写一个Java套接字服务器从该服务器将图像发送到导航器客户端)。但是当我发送图像时文件似乎损坏显示带有符号的图像)。

DataOutputStream dout = new DataOutputStream(connectS.getOutputStream());
String file = "image.jpg";
File filename = new File(file);
FileInputStream fin = new FileInputStream(filename);
// dout.writeUTF(file);
System.out.println("正在发送图像...");
int size = (int) filename.length();
byte[] readData = new byte[size];
fin.read(readData);
dout.writeInt(size);
dout.flush();
dout.write(readData, 0, size);
/*for(int i=0;i<readData.length;i++) {
     dout.write(readData, 0, i);
}*/
dout.flush();
这是我启动程序的方式

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

感谢您的帮助
英文:

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).

                DataOutputStream dout = new DataOutputStream(connectS.getOutputStream());
				String file=&quot;image.jpg&quot;;
                File filename = new File(file);
                FileInputStream fin = new FileInputStream(filename);  
                //dout.writeUTF(file);
                System.out.println(&quot;Sending image...&quot;);
                int size=(int) filename.length();
                byte[] readData = new byte[size]; 
                fin.read(readData);
                dout.writeInt(size);
                dout.flush();
                dout.write(readData,0,size);
                /*for(int i=0;i&lt;readData.length;i++) {
			         dout.write(readData, 0, i);
                }*/
                dout.flush();

Here is how I start the program

    ServerSocket ss=new ServerSocket(8080);
    Socket connectS=ss.accept();
	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:

确定