如何从套接字接收文件而不是其内容?

时间:2016-03-05 17:27:28

标签: java sockets

我有一个服务器为客户端返回文件 photo.png ,当我引入此链接时,服务器正在运行,将客户端视为浏览器localhost:5555/photo.png我没有得到图片我明白了:

\89PNG

\00\00\00
IHDR\00\00\00\00\00\00\00\91\F9\00\00\00gAMA\00\00\B1\8F\FCa\00\00\00sRGB\00\AE\CE\E9\00\00\00PLTELiq\EA\F2\F7\F2\F4\F8\FB\EF\EF\E9\F1\F7\EA\F2\F8\EC\F3\F8\FC\EC\EB\FB\ED\EE\E4\EF\F7\FB\EC\EC\FB\ED\ED\FB\ED\ED\ED\F4\F9\FB\EF\EF\FD\ED\ED\EB\EB\EB\FB\EB\EB\F9\EE\EF\FA\EB\EB\EE\F4\F8\F2\F2\F2\FB\E9\E9\E9\F1\F8\EA\F1\F8\EC\F3\F8\FB\E9\EA\E6\F0\F6\E7\F1\F7\FC\EF\EF\EA\F1\F6\EF\EF\EF\ED\F3\F7\ED\F3\F8\E7\F0\F7\FA\EE\EE\FA\E9\E9\EA\F0\F8\ED\F2\F9\EA\F3\F9\F3\F2\F4\FC\EC\EB\E1"o\B6\E0"\E1!\E0!\E1!  n\B5\E0 \E0k\B4\00f\B2n\B6\E0m\B5   n\B6\00g\B2\E0\E0\DFj\B3\00a\AF\DF\00e\B1l\B4\00i\B3\DF\E0!l\B5\00h\B2\DF\00`\AE    m\B5\E0\E1"\DF\DF\00c\B0\E47:\DF
\E2'*\E0\E5:<\DE    \DE\DF\00d\B0\00_\AE\F2\9D\9F\DE
y\BB\DF ........

这是image photo.png背后的代码或文字,但应显示的是: photo.ong

当我需要PDF文件时,我会得到代码而不是文件......

import java.io.*;
import java.net.*;

    public class Server {
        public static void main (String[] args){
            Socket socket;
            ServerSocket serverSocket;
            BufferedReader in = null;
            PrintWriter out = null;
            BufferedInputStream bis;
            BufferedOutputStream bos;

            try{
                serverSocket=new ServerSocket(5555);
                socket = serverSocket.accept();
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String input, output;

                input = in.readLine(); //(1)
                out.println("Server: Connected. Input from Client:"+input); //(2)

                input = in.readLine(); //(1)
                out.println("Server: I am ready to recieve file.  Input from Client:"+input); //(2)



                bis = new BufferedInputStream(socket.getInputStream());
                bos = new BufferedOutputStream(new FileOutputStream("photo.png"));
                int length = Integer.parseInt(input);
                int i=0;
                int IN=0; 
                byte[] receivedData = new byte[1000];
                while ((IN = bis.read(receivedData)) != length){ //in = int; receivedData = byte[]
                    bos.write(receivedData,0,IN);
                }



            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }

此服务器由http://www.coderanch.com

实施

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试对图像执行文件IO操作。请参阅以下内容:

How to make ImageIO read from InputStream :Java