客户端 - 服务器:从Android到PC的文件传输通过套接字和来自服务器的响应连接

时间:2013-07-17 14:38:59

标签: android sockets client-server transfer

我是Java和Andriod的新手。我试过这个例子:

Client-Server: File transfer from Android to PC connected via socket

它完美无缺。现在我想从服务器回复任何消息,我不能这样做。这是代码:

服务器端:

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\\Gustavo\\Desktop\\WebOffice.jpg"); // destination path and name of file
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(mybytearray,0,mybytearray.length);
            current = bytesRead;

            // Recibe el File JPG
            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();

            //RESPONSE FROM THE SERVER
            PrintWriter out = new PrintWriter(sock.getOutputStream(), true); 
            out.println(99); //REPLY DE NUMBER 99

            out.close();


          sock.close();
          }
    }   
}

客户方:

package com.example.sclient;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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); 
                    sock = new Socket("192.168.0.12", 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();

                          //RESPONSE FROM THE SERVER
                          BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                          in.ready();
                          String userInput = in.readLine();
                          System.out.println("Response from server..." + userInput);

                        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);
    }
}

1 个答案:

答案 0 :(得分:4)

古斯塔沃, 传输完成得很好,但只要服务器不知道您发送了多少数据,它就会在读取循环中等待,直到您关闭套接字或发生超时。为了让服务器知道你已经发送了整个数据,必须关闭套接字输出,这样,服务器将收到该指示,read()返回0.然后服务器将99消息发送给客户端。

例如:

在服务器上:

int ret=0;
int offset=0;
byte[] mybytearray = new byte[filesize];
while ((ret = is.read(mybytearray, offset, filesize -offset)) > 0)
{
    offset+=ret;
    // just in case the file is bigger that the buffer size
   if (offset >= filesize) break;
}
bos.write(mybytearray, 0 , offset);            
bos.flush();            
long end = System.currentTimeMillis();            
System.out.println(end-start);            
bos.close();
// RESPONSE FROM THE SERVER            
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);            
out.println(99); //REPLY DE NUMBER 99
out.close();

在客户端:

System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
// RESPONSE FROM THE SERVER 
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
in.ready(); 
// tell the receiver we are done sending
sock.shutdownOutput();
String userInput = in.readLine();                          
System.out.println("Response from server..." + userInput);