ошибки Java TCP должны быть исправлены - PullRequest
0 голосов
/ 16 января 2011

Я кодировал два класса, работающих как клиент и сервер, они могут передавать файл в обоих направлениях, есть некоторые ошибки, первая ошибка, когда я решаю выгрузить файл с клиента на сервер, файл может быть успешно загружен,однако процесс сервера будет остановлен исключением нулевого указателя из InputStream pis = connectionSocket.getInputStream ();вторая ошибка - когда вы успешно загрузили и хотите проверить другую загрузку, он не будет передавать файл должным образом, но если вы загрузите его в третий раз, он снова будет работать хорошо, странно.следующий код - то, что я получил, когда он просит вас ввести имя файла, вы должны ввести что-то вроде c: \ users \ file.file.надеюсь, кто-то может помочь мне с этим, большое спасибо.tcpserver.java

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

 class TCPServer {

public static void main(String args[]) {
    String direction="";
    String filename="";
    byte[] aByte = new byte[1];
    int bytesRead;

    while (true) {
        ServerSocket welcomeSocket = null;
        Socket connectionSocket = null;
        BufferedOutputStream outToClient = null;
        BufferedReader inFromClient =null;

        try {
            welcomeSocket = new ServerSocket(3248);
            connectionSocket = welcomeSocket.accept();
            outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            System.out.println("connection is established with               "+connectionSocket.getInetAddress()+"using port "+connectionSocket.getPort());
             inFromClient =new BufferedReader(
 new InputStreamReader(connectionSocket.getInputStream()));

             direction = inFromClient.readLine();
             System.out.println("client wants to "+direction);
             filename=inFromClient.readLine();
             System.out.println("file directory and name is "+filename);



        } catch (IOException ex) {
            // Do exception handling
        }

        if (outToClient != null&&direction.equals("download")) {
            File myFile = new File(filename);
            byte[] mybytearray = new byte[(int) myFile.length()];

            FileInputStream fis = null;

            try {
                fis = new FileInputStream(myFile);
            } catch (FileNotFoundException ex) {
                System.out.println("can't find file");
                // Do exception handling
            }
            BufferedInputStream bis = new BufferedInputStream(fis);

            try {
                bis.read(mybytearray, 0, mybytearray.length);
                outToClient.write(mybytearray, 0, mybytearray.length);
                outToClient.flush();
                outToClient.close();
                connectionSocket.close();
                fis.close();
                bis.close();
                inFromClient.close();


            } catch (IOException ex) {
                // Do exception handling
            }
        }
        if(direction.equals("upload"))
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //byte[] yourByteArray = new byte[10240];
            File serverFile = new File(filename);
            FileOutputStream fos = null;
        BufferedOutputStream bos = null;

         try {
            InputStream pis = connectionSocket.getInputStream();
            fos = new FileOutputStream(filename);
            bos = new BufferedOutputStream(fos);
            bytesRead = pis.read(aByte, 0, aByte.length);

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

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

        System.out.println("The file transmission finishes!");

    }
}
}

}

TCPClient.java

    import java.io.*;

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

class TCPClient {

public static void main(String args[]) {
    byte[] aByte = new byte[1];
    int bytesRead;
    String downloadfile;
    String downloadfilere;
    String uploadfile;
    String uploadfilese;
    Socket clientSocket = null;
    InputStream is = null;
    String ip;
    int port;
    String conti;

    boolean goon=true;
    int situation;
    Scanner sc=new Scanner(System.in);
    Scanner sc1=new Scanner(System.in);
    Scanner sc2=new Scanner(System.in);
    System.out.println("please input the ip address for the host");
    ip=sc.nextLine();
    System.out.println("please input the port number");
    port=sc.nextInt();
    DataOutputStream outToServer=null;
    BufferedOutputStream fileoutToServer = null;



    while(goon=true){
    try {
        clientSocket = new Socket(ip, port);
        is = clientSocket.getInputStream();
        System.out.println("connection is established");
         outToServer = new DataOutputStream(clientSocket
.getOutputStream());
    } catch (IOException ex) {
        // Do exception handling
    }

    System.out.println("what request do you want to make:    "+"\n"+"1.download"+"\n"+"2.upload");
    situation=sc.nextInt();
    if(situation==1){
       try{ outToServer.writeBytes("download"+ "\n");
       outToServer.flush();}catch(IOException ex){}
        System.out.println("please enter the file name for download");
        downloadfile=sc1.nextLine();
        //try{ outToServer.writeBytes("download"+ "\n");}catch(IOException ex){}
        System.out.println("please enter the file name you want the received file to be saved as");
       downloadfilere=sc2.nextLine();
       try{ outToServer.writeBytes(downloadfile+ "\n");
       outToServer.flush();
       }catch(IOException ex){}

    if(downloadfile!=""){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    if (is != null) {

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream(downloadfilere);
            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();
            clientSocket.close();
        } catch (IOException ex) {
            // Do exception handling
        }
    }}
    System.out.println("file received successfully");
    }
    if(situation==2)
    {
        try{ outToServer.writeBytes("upload"+ "\n");}catch(IOException ex){}
        System.out.println("please enter the file name for upload");
        uploadfile=sc1.nextLine();
        System.out.println("please enter the file name on server for upload");
        uploadfilese=sc2.nextLine();
        try{ outToServer.writeBytes(uploadfilese+ "\n");}catch(IOException ex){}

        File myFile = new File(uploadfile);
        byte[] yourByteArray = new byte[1024];//*
        try{
          FileInputStream pfis = new  FileInputStream(myFile);
         //BufferedInputStream bbis=new BufferedInputStream(pfis);
         int pnread=0;
        OutputStream pbos = clientSocket.getOutputStream();
                       //System.out.println("pfis.read(yourByteArray)"+pfis.read(yourByteArray));//***
           while((pnread=pfis.read(yourByteArray))>0)
        {
         pbos.write(yourByteArray, 0, pnread);
        //System.out.println("pfis.read(yourByteArray)"+pnread);//***
           pbos.flush();
          }
          pbos.close();
        }catch(IOException ex){}


    }

    System.out.println("do you want to do another request?");
    conti=sc.nextLine();
    if(conti.equals("yes"))
        goon=true;
    else 
        goon=false;
    //try{clientSocket.close();}catch(IOException ex){}
}
}

}

сообщение об ошибке:

    Exception in thread "main" java.lang.NullPointerException
    at TCPServer.main(TCPServer.java:79)
    Java Result: 1

Ответы [ 2 ]

3 голосов
/ 16 января 2011

исключение нулевого указателя из InputStream pis = connectionSocket.getInputStream ()

Таким образом, 'connectionSocket' является нулевым.Это происходит из-за вашей неправильной структуры обработки исключений.Подумайте, что произойдет, если вам не удастся создать 'connectionSocket', а затем продолжите работу с кодом после блока catch.Весь код, использующий connectionSocket, должен находиться внутри блока try, который его создает.

Вы также игнорируете результат метода read () и предполагаете, что он вернул максимально возможный объем данных.Это не указано для этого.Вы должны иметь что-то вроде этого:

int count;
while ((count = in.read(buffer)) > 0)
  out.write(buffer, 0, count);
1 голос
/ 16 января 2011

Я подозреваю, что проблема в том, что вы звоните connectionSocket.getInputStream дважды.Вы должны получить поток только один раз и использовать его на протяжении всего времени процесса подключения.

Это не связано, но почему у вас есть три Scanner экземпляра в классе клиента?Вам нужен только один.Все они читают из одного и того же основного потока (System.in).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...