2012-01-19 121 views
5

需要幫助...我已經理解如何使服務器 - 客戶端套接字連接...它工作fie ...現在我想從服務器傳輸文件到客戶端,並返回....這裏是我的消息來源......android套接字文件傳輸

套接字服務器...

public class ServerActivity extends Activity { 

private TextView serverStatus; 

// default ip 
public static String SERVERIP = "192.168.1.1"; 

// designate a port 
public static final int SERVERPORT = 8080; 

private Handler handler = new Handler(); 

private ServerSocket serverSocket; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    serverStatus = (TextView) findViewById(R.id.server_status); 

    SERVERIP = getLocalIpAddress(); 

    Thread fst = new Thread(new ServerThread()); 
    fst.start(); 
} 

public class ServerThread implements Runnable { 

    public void run() { 
     try { 
      if (SERVERIP != null) { 
       handler.post(new Runnable() { 
        @Override 
        public void run() { 
         serverStatus.setText("Listening on IP: " + SERVERIP); 
        } 
       }); 
       serverSocket = new ServerSocket(SERVERPORT); 
       while (true) { 
        // listen for incoming clients 


        Socket client = serverSocket.accept(); 
        ///////////////////////////////// 
        File myFile = new File ("/sdcard/frostwire.apk"); 
        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 = client.getOutputStream(); 
        System.out.println("Sending..."); 
        serverStatus.setText("sending 123.exe..."); 
        os.write(mybytearray,0,mybytearray.length); 
        os.flush(); 
        client.close(); 
        //////////////////////////// 

        handler.post(new Runnable() { 
         @Override 
         public void run() { 
          serverStatus.setText("Connected."); 
         } 
        }); 

        try { 
         BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
         String line = null; 
         while ((line = in.readLine()) != null) { 
          Log.d("ServerActivity", line); 
          handler.post(new Runnable() { 
           @Override 
           public void run() { 
            // do whatever you want to the front end 
            // this is where you can be creative 
           } 
          }); 
         } 
         break; 
        } catch (Exception e) { 
         handler.post(new Runnable() { 
          @Override 
          public void run() { 
           serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones."); 
          } 
         }); 
         e.printStackTrace(); 
        } 
       } 
      } else { 
       handler.post(new Runnable() { 
        @Override 
        public void run() { 
         serverStatus.setText("Couldn't detect internet connection."); 
        } 
       }); 
      } 
     } catch (Exception e) { 
      handler.post(new Runnable() { 
       @Override 
       public void run() { 
        serverStatus.setText("Error"); 
       } 
      }); 
      e.printStackTrace(); 
     } 
    } 
} 

// gets the ip address of your phone's network 
private String getLocalIpAddress() { 
    try { 
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
      NetworkInterface intf = en.nextElement(); 
      for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
       InetAddress inetAddress = enumIpAddr.nextElement(); 
       if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } 
      } 
     } 
    } catch (SocketException ex) { 
     Log.e("ServerActivity", ex.toString()); 
    } 
    return null; 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    try { 
     // make sure you close the socket upon exiting 
     serverSocket.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

} 

客戶端的Socket ...源

public class ClientActivity extends Activity { 

private EditText serverIp; 

private Button connectPhones; 

private String serverIpAddress = ""; 

private boolean connected = false; 

private Handler handler = new Handler(); 
int filesize; // filesize temporary hardcoded 

long start = System.currentTimeMillis(); 
int bytesRead; 
int current = 0; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.client); 

    serverIp = (EditText) findViewById(R.id.server_ip); 
    connectPhones = (Button) findViewById(R.id.connect_phones); 
    connectPhones.setOnClickListener(connectListener); 
} 

private OnClickListener connectListener = new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     if (!connected) { 
      serverIpAddress = serverIp.getText().toString(); 
      if (!serverIpAddress.equals("")) { 
       Thread cThread = new Thread(new ClientThread()); 
       cThread.start(); 
      } 
     } 
    } 
}; 

public class ClientThread implements Runnable { 

    public void run() { 
     try { 
      InetAddress serverAddr = InetAddress.getByName(serverIpAddress); 
      Log.d("ClientActivity", "C: Connecting..."); 
      Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT); 
      connected = true; 
    //////////  // receive file 
      byte [] mybytearray = new byte [filesize]; 
      InputStream is = socket.getInputStream(); 
      FileOutputStream fos = new FileOutputStream("/sdcard/frostwire.apk"); 
      BufferedOutputStream bos = new BufferedOutputStream(fos); 
      bytesRead = is.read(mybytearray,0,mybytearray.length); 
      current = bytesRead; 


      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(); 
      socket.close(); 

    //////////////////////////////  
      while (connected) { 
       try { 
        Log.d("ClientActivity", "C: Sending command."); 
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket 
           .getOutputStream())), true); 
         // where you issue the commands 
         out.println("Hey Server!"); 
         Log.d("ClientActivity", "C: Sent."); 
       } catch (Exception e) { 
        Log.e("ClientActivity", "S: Error", e); 
       } 
      } 
      socket.close(); 
      Log.d("ClientActivity", "C: Closed."); 
     } catch (Exception e) { 
      Log.e("ClientActivity", "C: Error", e); 
      connected = false; 
     } 
    } 
} 
} 

件所生產的 「///////」 唐標't work ....幫助

+0

只是說「它不起作用」並不是什麼線索......你可能試着更好地解釋它嗎?它可以幫助我們幫助你。 –

+0

套接字服務器提供了一個錯誤...據我所知,錯誤是: – timonvlad

+0

byte [] mybytearray = new byte [filesize]; InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream(「/ sdcard/frostwire.apk」); BufferedOutputStream bos = new BufferedOutputStream(fos); bytesRead = is.read(mybytearray,0,mybytearray.length); current = bytesRead; do { bytesRead = is.read(mybytearray,current,(mybytearray.length-current)); if(bytesRead> = 0)current + = bytesRead; – timonvlad

回答

1


更好您替換下面的代碼

do { 
       bytesRead = 
        is.read(mybytearray, current, (mybytearray.length-current)); 
       if(bytesRead >= 0) current += bytesRead; 
      } while(bytesRead > -1); 

用下面的

do { 
       bytesRead =is.read(mybytearray, current, (mybytearray.length-current)); 
       if(bytesRead > 0) 
       { 
        current += bytesRead; 
       } 
    } while(bytesRead > 0); 


那就試試吧

0

通過上面的討論會後,我想補充一些評論 -

  1. 你有沒有在Android清單文件中添加讀取sdcard的權限代碼?如果沒有,則應在服務器訪問外部存儲器時添加以下代碼。爲客戶做也寫在外部存儲。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 

  • 否則,你提供的目錄是不正確的。檢查目錄。

  • 在客戶端程序中,您已經定義了file_size,該程序中沒有任何值沒有賦值。

  • 我還想建議,客戶端程序中的file_size應該大於要傳輸的文件,大小以字節爲單位。