发送一个整数值,然后在java中从客户端发送整个文件到服务器

时间:2014-01-05 17:54:24

标签: java file-upload client-server

基本上,这就是我所做的: - 客户端

public class Client {

    public String uploadFile(String filePath,int language) throws Exception {
        Socket sock = new Socket("127.0.0.1", 25000);


        // make the file object from filepath
        File myFile = new File(filePath);

        // send the integer 'language'
        OutputStream os = sock.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(language);
        bw.flush();

        // send the file data
        byte[] mybytearray = new byte[(int) myFile.length()];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                myFile));
        bis.read(mybytearray, 0, mybytearray.length);
        os.write(mybytearray, 0, mybytearray.length);
        os.flush();
        bis.close();

        // get the reply
        InputStream is = sock.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String message = br.readLine();

        sock.close();

        return message;

    }
}

服务器端: -

 void connectToNewClient(Socket sock) throws IOException,
            InterruptedException {

        // get the integer 'language'

        InputStream is = sock.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String language = br.readLine();

        // Read file data sent by client and store in server
        byte[] mybytearray = new byte[50000];
        FileOutputStream fos = new FileOutputStream("Main.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int bytesRead = is.read(mybytearray, 0, mybytearray.length);
        bos.write(mybytearray, 0, bytesRead);
        bos.close();

        // give back response
        OutputStream os = sock.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(response);

        bw.flush();

        sock.close();

    }

所以我的问题是,当我只从客户端发送文件或只发送整数时,我可以在服务器端接收它们,但是,当我尝试将它们一起发送时,我在服务器端没有收到任何信息。猜猜我搞砸了这么多作家对象和数据流对象。请帮助我出错了。谢谢。 注意:我删除了几行代码,我认为这些代码与我的问题无关。

1 个答案:

答案 0 :(得分:0)

您将流包装在BufferedWriter中,由于多种原因,这通常是一件好事。您的代码的奇怪之处在于您正在使用该编写器用于Integer,以及用于文件的未包装的OutputStream。我怀疑在没有重新实现编写器的情况下不能使用这两个写操作。

我建议你只使用一个编写器来重构你的代码。我会选择更通用的ObjectOutputStream,它允许您发送实现Serializable接口的对象(您的场景已满足此约束)。您可以通过ObjectInputStream直接接收对象。