客户端-服务器:从 Android 到通过套接字连接的 PC 的文件传输
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10417442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Client-Server: File transfer from Android to PC connected via socket
提问by Arwa A
I'm trying to send a picture I choose from the gallery on my phone, and send that picture from the phone to my PC, when I click on the button it should take the picture's path and put it in a file, and transfer it to my PC. I've checked the code on my PC - for both sides - and it worked totally fine.
我正在尝试发送我从手机图库中选择的图片,然后将该图片从手机发送到我的 PC,当我单击该按钮时,它应该采用图片的路径并将其放入文件中,然后进行传输到我的电脑。我已经检查了我 PC 上的代码 - 双方 - 并且它工作得很好。
When I test it out, nothing happens!
当我测试它时,没有任何反应!
Here is the code:
这是代码:
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();
}
}
}
Client side (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);
}
}
XML code:
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>
回答by Alaa
you have just to add the permission
你只需要添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
and it will work perfect.
它将完美运行。
回答by Narendra Rathore
Instead of trying it in emulator on PC try to run the same on a mobile device. Also I have changed the Port number to 8000 instead of using 1149 port.
与其在 PC 上的模拟器中尝试,不如尝试在移动设备上运行它。此外,我已将端口号更改为 8000 而不是使用 1149 端口。
With these changes the code worked fine for me. Please check.
通过这些更改,代码对我来说效果很好。请检查。
回答by adnaan.zohran
It aint working cos u havn't reintialized your variable current to 0 It seems your are apending in the subsequent loop without reseting the value. So in my guess it might be causing problem in the second iteration of your execution.
它不能正常工作,因为你没有将可变电流重新初始化为 0 似乎你在没有重置值的情况下在后续循环中挂起。所以在我看来,它可能会在执行的第二次迭代中引起问题。