2012-05-02 19 views
13

Tôi đang cố gắng gửi ảnh tôi chọn từ thư viện trên điện thoại của mình và gửi ảnh đó từ điện thoại đến máy tính của tôi, khi tôi nhấp vào nút nó nên lấy đường dẫn của hình ảnh và đặt nó trong một tập tin, và chuyển nó vào máy tính của tôi. Tôi đã kiểm tra mã trên máy tính của tôi - cho cả hai bên - và nó hoạt động hoàn toàn tốt.Máy khách-Khách: Chuyển tệp từ Android sang PC được kết nối qua cổng

Khi tôi thử nghiệm, không có gì xảy ra!

Đây là mã:

Server side:

import java.io.*; 
import java.net.*; 

public class FileServer { 

    public static void main(String[] args) throws IOException { 
     int filesize=6022386; // filesize temporary hardcoded 

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

     // create socket 
     ServerSocket servsock = new ServerSocket(1149); 
     while (true) { 
      System.out.println("Waiting..."); 

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

     // receive file 
      byte [] mybytearray = new byte [filesize]; 
      InputStream is = sock.getInputStream(); 
      FileOutputStream fos = new FileOutputStream("C:\\Users\\Arwa\\Documents\\WebOffice.jpg"); // destination path and name of file 
      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(); 
      } 
    } 

} 

Khách hàng bên (Android):

package com.arwa.file.send; 

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.ObjectOutputStream; 
import java.io.OutputStream; 
import java.net.Socket; 
import java.net.UnknownHostException; 

import android.app.Activity; 
import android.content.Intent; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.TextView; 

public class SendfileActivity extends Activity { 
    /** Called when the activity is first created. */ 

    private static final int SELECT_PICTURE = 1; 

    private String selectedImagePath; 
    private ImageView img; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     System.out.println("34"); 
     img = (ImageView) findViewById(R.id.ivPic); 
     System.out.println("36"); 
     ((Button) findViewById(R.id.bBrowse)) 
       .setOnClickListener(new OnClickListener() { 
        public void onClick(View arg0) { 
         System.out.println("40"); 
         Intent intent = new Intent(); 
         intent.setType("image/*"); 
         intent.setAction(Intent.ACTION_GET_CONTENT); 
         startActivityForResult(
           Intent.createChooser(intent, "Select Picture"), 
           SELECT_PICTURE); 
         System.out.println("47"); 
        } 
       }); 
     ; 
     System.out.println("51"); 
     Button send = (Button) findViewById(R.id.bSend); 
     final TextView status = (TextView) findViewById(R.id.tvStatus); 

     send.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       Socket sock; 
       try { 
        sock = new Socket("MY_PCs_IP", 1149); 
        System.out.println("Connecting..."); 

        // sendfile 
          File myFile = new File (selectedImagePath); 
          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(); 
       } catch (UnknownHostException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 



      } 
     }); 
    } 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode == RESULT_OK) { 
      if (requestCode == SELECT_PICTURE) { 
       Uri selectedImageUri = data.getData(); 
       selectedImagePath = getPath(selectedImageUri); 
       TextView path = (TextView) findViewById(R.id.tvPath); 
       path.setText("Image Path : " + selectedImagePath); 
       img.setImageURI(selectedImageUri); 
      } 
     } 
    } 

    public String getPath(Uri uri) { 
     String[] projection = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = managedQuery(uri, projection, null, null, null); 
     int column_index = cursor 
       .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } 
} 

mã XML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/tvStatus" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/hello" /> 

    <TextView 
     android:id="@+id/tvPath" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Path: " /> 

    <Button 
     android:id="@+id/bBrowse" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Browse" > 
    </Button> 

    <Button 
     android:id="@+id/bSend" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Send" /> 

    <ImageView 
     android:id="@+id/ivPic" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" > 
    </ImageView> 

</LinearLayout> 
+0

Khi chạy từ trình mô phỏng, IP khác với trong "thế giới thực" giá trị của MY_PCs_IP là bao nhiêu? 10.0.2.2? và IP của máy chủ? –

+0

giá trị của nó là IP của PC của tôi, vì tôi đang kết nối qua WiFi –

Trả lời

2

bạn chỉ cần thêm quyền

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<uses-permission android:name="android.permission.INTERNET"/> 

và nó sẽ hoạt động hoàn hảo.

1

Thay vì thử nó trong trình giả lập trên PC, hãy thử chạy giống nhau trên thiết bị di động. Ngoài ra tôi đã thay đổi số cổng thành 8000 thay vì sử dụng cổng 1149.

Với những thay đổi này, mã hoạt động tốt cho tôi. Hãy kiểm tra.

0

Nó aint làm việc cos u không reintialized biến hiện tại của bạnCó vẻ như bạn đang chờ trong vòng lặp tiếp theo mà không cần đặt lại giá trị. Vì vậy, trong tôi đoán nó có thể gây ra vấn đề trong lần lặp thứ hai của bạn thực hiện.