报错如下
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at com.gaoyunfeng.uplooking.www.server.AndroidServer.main
- Java code
package com.download;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;public class DownloadFileActivity extends Activity { public ProgressBar pb; Button btn; int progress = 0; MyAnysTask myAnysTask; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); pb = (ProgressBar) findViewById(R.id.progressBar1); btn = (Button) findViewById(R.id.button1); btn.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub myAnysTask = new MyAnysTask(); myAnysTask.execute("a1.mp3"); btn.setEnabled(false); } }); } @Override protected void onDestroy() { finish(); // TODO Auto-generated method stub super.onDestroy(); } class MyAnysTask extends AsyncTask<String, Integer, String> { @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub progress += values[0]; pb.setProgress(progress); super.onProgressUpdate(values); } @Override protected String doInBackground(String... params) { Socket socket = null; InputStream inputStream = null ; OutputStream outputStream = null ; OutputStream fileout = null; try { socket = new Socket("192.168.1.100", 9999); byte[] buffer = new byte[8 * 1024]; inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); outputStream.write(params[0].getBytes()); // 设置pb的max inputStream.read(buffer); System.out.println("buffer"+new String(buffer).trim()); if (new String(buffer).trim() != null) { int filecinmax = Integer.parseInt(new String(buffer).trim()); pb.setMax(filecinmax); } outputStream.write("hello".getBytes()); // 开始下载文件 File file = new File("/sdcard/a1.mp3"); if (file.exists()) { file.delete(); } file.createNewFile(); int count = 0; fileout = new FileOutputStream(file); do { count = inputStream.read(buffer); fileout.write(buffer, 0, count); publishProgress(8); } while (count == buffer.length); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { fileout.close(); inputStream.close(); outputStream.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } }}