0

您好,我有 2 个类可以将文件推送到 android 设备中。

我的服务器类:

    public class FileServer {
      public static void main (String [] args ) throws IOException {
        // create socket
        ServerSocket servsock = new ServerSocket(13267);
        while (true) {
          System.out.println("Waiting...");

          Socket sock = servsock.accept();
          System.out.println("Accepted connection : " + sock);

          // sendfile
          File myFile = new File ("C:\\Users\\Petrica\\Desktop\\zzz.txt");
          byte [] mybytearray  = new byte [(int)myFile.length()];
          FileInputStream fis = new FileInputStream(myFile);
          BufferedInputStream bis = new BufferedInputStream(fis);
          bis.read(mybytearray,0,mybytearray.length);
          OutputStream os = sock.getOutputStream();
          System.out.println("Sending...");
          os.write(mybytearray,0,mybytearray.length);
          os.flush();
          sock.close();
          }
        }
    }

And my Client Class:

public class TCPClient extends AsyncTask{
@Override
protected Object doInBackground(Object... params) {
    int filesize=6022386; // filesize temporary hardcoded

    long start = System.currentTimeMillis();
    int bytesRead;
    int current = 0;
    // localhost for testing
    Socket sock = null;
    try {
        sock = new Socket("127.0.0.1",13267);
    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    System.out.println("Connecting...");

    // receive file
    try {
    byte [] mybytearray  = new byte [filesize];
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream("/mnt/sdcard/zzz.txt");
    BufferedOutputStream bos = new BufferedOutputStream(fos);

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


    current = bytesRead;

    // thanks to A. Cádiz for the bug fix
    do {
       bytesRead =
          is.read(mybytearray, current, (mybytearray.length-current));
       if(bytesRead >= 0) current += bytesRead;
    } while(bytesRead > -1);

    bos.write(mybytearray, 0 , current);
    bos.flush();
    long end = System.currentTimeMillis();
    System.out.println(end-start);
    bos.close();
    sock.close();
    // TODO Auto-generated method stub

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    return null;
}
}

我收到一个错误

    09-09 15:52:39.261: E/AndroidRuntime(802): FATAL EXCEPTION: AsyncTask #1
09-09 15:52:39.261: E/AndroidRuntime(802): java.lang.RuntimeException: An error occured while executing doInBackground()
09-09 15:52:39.261: E/AndroidRuntime(802):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-09 15:52:39.261: E/AndroidRuntime(802):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-09 15:52:39.261: E/AndroidRuntime(802):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-09 15:52:39.261: E/AndroidRuntime(802):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-09 15:52:39.261: E/AndroidRuntime(802):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-09 15:52:39.261: E/AndroidRuntime(802):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-09 15:52:39.261: E/AndroidRuntime(802):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-09 15:52:39.261: E/AndroidRuntime(802):  at java.lang.Thread.run(Thread.java:841)
09-09 15:52:39.261: E/AndroidRuntime(802): Caused by: java.lang.NullPointerException
09-09 15:52:39.261: E/AndroidRuntime(802):  at com.aaaaaa.TCPClient.doInBackground(TCPClient.java:33)
09-09 15:52:39.261: E/AndroidRuntime(802):  at com.aaaaaa.TCPClient.doInBackground(TCPClient.java:1)
09-09 15:52:39.261: E/AndroidRuntime(802):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-09 15:52:39.261: E/AndroidRuntime(802):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-09 15:52:39.261: E/AndroidRuntime(802):  ... 4 more

主要活动:

  public class MainActivity extends Activity {
    TCPClient tcpc;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
            Button btn = (Button) findViewById(R.id.send_button);
            btn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
            tcpc.execute();
                }
            });
        }


}

有谁知道我该怎么办???将来我想发送 2 个文件:D。谢谢您的建议。

4

2 回答 2

1

NullPointerExceptions:至少我希望你真的能够整理出你自己的东西,但是当你超越它时,你的复制代码是错误的。您目前忽略返回的计数read()并假设它已填充缓冲区。不能保证这样做。请参阅 Javadoc。

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

在两端使用它,任何缓冲区大小 > 0,通常为 8192。

于 2013-09-09T22:18:04.153 回答
0

我不认为你的 Socket 正在连接,但很难说。在您的日志输出中,它显示由 doInBackground() 第 33 行引起的 NullPointerException。您应该在编辑器中检查第 33 行,更好的是,在您的帖子中向我们展示第 33 行。我有一种感觉,您称之为 Socket sock = null;,然后你尝试在 try 块中实例化一个新的 Socket,但是失败了,所以 sock 仍然 == null,然后你在 sock 上调用一个方法,然后繁荣,NPE。

如果您在计算机上运行服务器,而在 Android 设备上运行 AsyncTask,您将无法尝试连接到 localhost (127.0.0.1)。相反,您应该尝试连接到计算机的内部网络 IP(例如 192.168.1.XXX),假设两个设备都在 WiFi 上。如果您正在运行 android 模拟器,则 127.0.0.1 指回模拟设备,并且所有模拟器会话都在模拟路由器上运行,您必须先配置端口转发才能引用开发机器,请参见此处- > http://developer.android.com/tools/devices/emulator.html#emulatornetworking

正如 Andras Balazs Lajtha 所说,看起来 TCPClient 在 onCreate() 期间从未初始化/创建,它只是被声明了。由于您的 logcat 输出显示来自 TCPClient 的错误,我假设您实际运行了该代码。

通常,当您发布涉及特定代码行问题的日志输出时,您应该从那里开始,并且当您发布时,请告诉我们或向我们展示那是哪一行。当然,如果第 33 行与 null Socket 对象无关,那么我根本没有太多帮助 :)

于 2013-09-09T22:17:06.713 回答