开发者

java tcp bugs need to be fixed

I have coded two classes working as client and server, they can transmit file on both direction, there are some bugs, the first bug is when I choose to upload a file from client to server, the file can be uploaded successfully, however, the server process will be stopped by a null pointer exception from InputStream pis = connectionSocket.getInputStream(); the second bug is when you have downloaded successfully and want to test another download, it will not transmit the file properly, but if you download it for the third time, it will work well again, weird. the following code is what I've got, when it asks you to enter the file name you have to enter something like c:\users\file.file. hope someone can help me with it, thanks a lot. 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();
                   开发者_Python百科    //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){}
}
}

}

error message:

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


a null pointer exception from InputStream pis = connectionSocket.getInputStream()

So 'connectionSocket' is null. That happen because of your incorrect execption handling structure. Consider what happens if you fail to construct 'connectionSocket' and then continue with the code after the catch block. All the code that uses 'connectionSocket' should be inside the 'try' block that constructs it.

You are also ignoring the result of the read() method and assuming it returned the maximum possible amount of data. It isn't specified to do that. You should have something like this:

int count;
while ((count = in.read(buffer)) > 0)
  out.write(buffer, 0, count);


I suspect the problem is that you are calling connectionSocket.getInputStream twice. You should only get the stream once and use it for the lifetime of the connection process.

This is unrelated, but why do you have three Scanner instances in the client class? You only need one. They're all reading from the same underlying stream (System.in).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜