0

我正在尝试制作一些包含文件传输的程序。当然,我必须使用字符流进行一些客户端-服务器通信,并且我还需要使用字节流来传输文件。当我使用 println 方法表单 PrintWriter 和 BufferedReader 中的 readLine 时出现问题,因为 readLine 读取行但在流中留下 '\n' 并导致问题(我不是 100% 确定这是问题)在我尝试之后使用字节流传输文件。所以我需要摆脱那个角色,我尝试使用 Reader 类中的 read 方法,但我没有成功。该代码在不使用字符流媒体的情况下完美运行。注意 readLine 的调用如何影响 sizeOfFile。

服务器

import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private static int SERVER_PORT = 9999;
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(SERVER_PORT);
            System.out.println("Server je pokrenut");
            while (true) {
                Socket sock = ss.accept();
                new MultithreadServer(sock);
            }
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

服务器线程

import java.io.*;
import java.net.Socket;
import java.util.*;

public class MultithreadServer extends Thread {
    private Socket sock;
    BufferedReader inChar;
    PrintWriter outChar;
    BufferedInputStream in;
    BufferedOutputStream out;
    DataOutputStream outByte;
    public MultithreadServer(Socket sock) throws Exception {
        this.sock = sock;
        inChar = new BufferedReader(
            new InputStreamReader(sock.getInputStream()));
        outChar = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
            sock.getOutputStream())), true);
        in = new BufferedInputStream(sock.getInputStream());
        out = new BufferedOutputStream(sock.getOutputStream());
        outByte = new DataOutputStream(sock.getOutputStream());
        start();
    }
    public void run() {
        try {
            String request = inChar.readLine();
            System.out.println("Fajl: " + request);
            File file = new File(request);
            BufferedInputStream in = new BufferedInputStream(
                new FileInputStream(file));
            long sizeOfFile = (long) file.length();

            outChar.println("SOME_MESSAGE"); //PROBLEM

            byte[] buffer = new byte[4096];
            int len = 0;
            outByte.writeLong(sizeOfFile);
            long totalyTransfered = 0;
            while ((len = in.read(buffer, 0, buffer.length)) !=-1) {
                out.write(buffer, 0, len);
                totalyTransfered += len;
            }
            System.out.println("Total:" + totalyTransfered);
            out.flush();
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

客户

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

public class ClientServer {
 static int SERVER_PORT = 9999;
 public static void main(String[] args) throws Exception {
 InetAddress address = InetAddress.getByName("127.0.0.1");
 Socket sock = new Socket(address, SERVER_PORT);
  PrintWriter out = new PrintWriter(new BufferedWriter(
   new OutputStreamWriter(sock.getOutputStream())), true);
  BufferedReader inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  Reader readChar = new InputStreamReader(sock.getInputStream());

 System.out.println("File:");   // choosing file from server
 Scanner consoleInput = new Scanner(System.in);
 String file = consoleInput.next();
 out.println(file);

 DataInputStream in = new DataInputStream(sock.getInputStream());

 System.out.println("Type name of file:");  //choosing name for file on client
 String newFile = consoleInput.next();

 OutputStream outByte = new FileOutputStream(newFile);
 byte[] buffer = new byte[4096];


 System.out.println("aa"+inChar.readLine()+"aa");   //PROBLEM
 System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT");  //TRYING TO FIX THE  PROBLEM
   //       in.read(); in.read();                      // DIFFERENT TRY
   long sizeOfFile= in.readLong();                    // BUT IT STILL HAS INFLUENCE OF       sizeOfFile
 System.out.println("Size of file:" + sizeOfFile);

 long totalyTransfered= 0;
 int len = 0;
 while ((len = in.read(buffer,0,buffer.length)) != -1) {
  outByte.write(buffer, 0, len);
  System.out.println("In one pass:" + len);
  sizeOfFile-=len;
  totalyTransfered+=len;
 System.out.println("Total:" + totalyTransfered);
 if (sizeOfFile<=0)break; 
  }
   System.out.println("Available: "+in.available());
  outByte.flush();
  outByte.close();

}
}
4

1 回答 1

0

我修改了您的代码并成功进行了文件传输,很抱歉我没有时间解决您的代码中的问题,我认为您的代码并不简单:)。

但是请在下面找到您修改过的代码,它非常简单,我从这里引用了这段代码

class Server:
No changes

类客户端服务器:

public class ClientServer {

    static int SERVER_PORT = 9999;

    private static final String fileOutput = "C:\\testout.pdf";

    public static void main(String[] args) throws Exception {
        InetAddress address = InetAddress.getByName("127.0.0.1");

        Socket sock = new Socket(address, SERVER_PORT);
        InputStream is = sock.getInputStream();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(sock.getOutputStream())), true);
        BufferedReader inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        Reader readChar = new InputStreamReader(sock.getInputStream());

        System.out.println("File:");   // choosing file from server
        Scanner consoleInput = new Scanner(System.in);
        String file = consoleInput.next();
        out.println(file);

        DataInputStream in = new DataInputStream(sock.getInputStream());

        System.out.println("Type name of file:");  //choosing name for file on client
        //String newFile = consoleInput.next();
        //
        //      OutputStream outByte = new FileOutputStream(newFile);
        //      byte[] buffer = new byte[4096];
        //
        //
        //      System.out.println("aa"+inChar.readLine()+"aa");   //PROBLEM
        //      System.out.println("SOME_TEXT"+readChar.read()+"SOME_TEXT");  //TRYING TO FIX THE  PROBLEM
        //      //       in.read(); in.read();                      // DIFFERENT TRY
        //      long sizeOfFile= in.readLong();                    // BUT IT STILL HAS INFLUENCE OF       sizeOfFile
        //      System.out.println("Size of file:" + sizeOfFile);
        //
        //      long totalyTransfered= 0;
        //      int len = 0;
        //      while ((len = in.read(buffer,0,buffer.length)) != -1) {
        //          outByte.write(buffer, 0, len);
        //          System.out.println("In one pass:" + len);
        //          sizeOfFile-=len;
        //          totalyTransfered+=len;
        //          System.out.println("Total:" + totalyTransfered);
        //          if (sizeOfFile<=0)break; 
        //      }
        //      System.out.println("Available: "+in.available());
        //      outByte.flush();
        //      outByte.close();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        int bytesRead;
        try {
            byte[] aByte = new byte[1];
            fos = new FileOutputStream(fileOutput);
            bos = new BufferedOutputStream(fos);

            bytesRead = is.read(aByte, 0, aByte.length);

            do {
                baos.write(aByte);
                bytesRead = is.read(aByte);
            } while (bytesRead != -1);

            bos.write(baos.toByteArray());
            bos.flush();
            bos.close();
            sock.close();
        } catch (IOException ex) {
            // Do exception handling
        }
    }
}

类多线程服务器:

public class MultithreadServer extends Thread {

    private Socket sock;
    BufferedReader inChar;
    PrintWriter outChar;
    BufferedInputStream in;
    BufferedOutputStream out;
    DataOutputStream outByte;

    public MultithreadServer(Socket sock) throws Exception {
        this.sock = sock;
        inChar = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        outChar = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
        in = new BufferedInputStream(sock.getInputStream());
        out = new BufferedOutputStream(sock.getOutputStream());
        outByte = new DataOutputStream(sock.getOutputStream());
        start();
    }

    public void run() {
        try {
            String request = inChar.readLine();
            System.out.println("Fajl: " + request);
            File file = new File(request);
            BufferedInputStream in = new BufferedInputStream(
                    new FileInputStream(file));

            byte[] buffer = new byte[(int) file.length()];

            FileInputStream fis = null;

            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException ex) {
                // Do exception handling
            }
            BufferedInputStream bis = new BufferedInputStream(fis);
            //long sizeOfFile = (long) file.length();

            //outChar.println("SOME_MESSAGE"); //PROBLEM

            //byte[] buffer = new byte[4096];
            try {
                bis.read(buffer, 0, buffer.length);
                out.write(buffer, 0, buffer.length);
                out.flush();
                out.close();
                sock.close();

                // File sent, exit the main method
                return;
            } catch (IOException ex) {
                // Do exception handling
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意:有少量未使用的代码行,请将其删除。希望它在星期天有帮助:) !!!

于 2012-08-19T20:32:15.080 回答