【问题标题】:java tcp bugs need to be fixedjava tcp错误需要修复
【发布时间】:2011-06-09 20:51:57
【问题描述】:

我编写了两个类作为客户端和服务器,它们可以双向传输文件,有一些错误,第一个错误是当我选择从客户端上传文件到服务器时,文件可以成功上传,但是,服务器进程将被 InputStream pis = connectionSocket.getInputStream(); 的空指针异常停止; 第二个BUG是当你下载成功了,想再试一次,文件不能正常传输,但是第三次​​下载,又能正常运行了,奇怪。下面的代码就是我所拥有的,当它要求您输入文件名时,您必须输入类似 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

【问题讨论】:

  • 您能否通过删除所有已注释掉的内容和其他不相关的内容来减少“代码墙”?另外,请包含异常的堆栈跟踪并标记行,以便人们可以准确地看到问题所在。
  • @Cameron:给您带来的不便,抱歉,我已经更新了代码,请看一下
  • InputStream pis = connectionSocket.getInputStream();是第 79 行,我把它写在问题中
  • 您的标题具有误导性。这些是您的代码中的错误,而不是 Java 或 TCP。

标签: java tcp


【解决方案1】:

一个空指针异常来自 输入流 pis = connectionSocket.getInputStream()

所以“connectionSocket”为空。发生这种情况是因为您不正确的执行处理结构。考虑如果您未能构造“connectionSocket”然后在 catch 块之后继续执行代码会发生什么。所有使用 'connectionSocket' 的代码都应该在构造它的 'try' 块内。

您还忽略了 read() 方法的结果,并假设它返回了最大可能的数据量。没有指定这样做。你应该有这样的东西:

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

【讨论】:

  • 感谢您的回答,但是使用connectionSocket的语法已经全部在try块中,这就是为什么我一直在收到异常感到困惑。
  • @starcaller:您在第二部分的 catch 块之后得到了异常。那也应该在 try 块内。
【解决方案2】:

我怀疑问题在于您调用了两次connectionSocket.getInputStream。您应该只获取一次流并在连接过程的整个生命周期内使用它。

这无关紧要,但是为什么客户端类中有三个Scanner 实例?你只需要一个。它们都从同一个底层流 (System.in) 中读取。

【讨论】:

  • 在更改调用connectionSocket.getInputStream一次后,它仍然无法正常工作,没有更多的空指针异常但服务器在第一个请求之后没有响应之前没有发生的其他请求,谢谢。
  • @Starcaller:我建议您使用调试器单步执行代码,或者添加大量 System.out.println 语句,以便您可以准确了解发生了什么。调试代码并不容易,需要练习。
  • 老实说,我在这些错误弹出的第一刻就已经这样做了,我正在寻求帮助 b/c 在打印大量 System.out 后我无法弄清楚发生了什么。 println
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
相关资源
最近更新 更多