从Pc发送文件到Android

时间:2017-04-18 20:27:09

标签: java android sockets

我在Android手机上用Java编写了这段代码:

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Handler;

public class Connection extends Thread {

    private boolean isBinded = false;
    private String IpAddress;
    private Context cx;
    private int  num;
    //private Socket socket;
    private InputStreamReader inRead;
    public ServerSocketChannel server;
    private volatile  boolean isRunning =true;
    private File fileRecieved =null;
    private FileOutputStream fos =null;
    private BufferedOutputStream bos =null;
    private File photoDir=null;
    private  ByteBuffer bufferByteSize=null;
    private  ByteBuffer bufferByte=null;
    private MediaPlayer playMe=null;
    private byte [] bytesToSend  = null;
    private MainActivity myActivity=null;
    private Handler handler =null;

    public Connection(String IpAddress, Context cx) {
        this.IpAddress = IpAddress;
        this.cx = cx;
        myActivity = new MainActivity();

        this.playMe = new MediaPlayer().create(cx, R.raw.sound1);
        photoDir = new File(Environment.getExternalStorageDirectory(), "/RecievedPhotoes");
        if (!photoDir.exists())
            photoDir.mkdir();
    }

    @Override
    public void run() {
        Looper.prepare();
        ToastHandler th = new ToastHandler(cx);//Toast handler is a class to handle toasts from threads 

        try {
            Selector selector = Selector.open();

            int[] ports = {5050, 4001, 6000};
            //   for (int port : ports) {
                server = ServerSocketChannel.open();
                server.configureBlocking(false);
                server.socket().bind(new InetSocketAddress(IpAddress, 5050));

                server.register(selector, SelectionKey.OP_ACCEPT);
                Log.d("msg", "1111");
                th.showToast("Registered", 1000);
            //  }

            while (true) {
                Log.d("Selector : ", "selector.isOpen()");
                selector.select();
                Log.d("Selector : ", "selector.select()");
                Set selectedkeys = selector.selectedKeys();
                Log.d("Selector : ", "selector.selectedKeys();");

                Iterator iterator = selectedkeys.iterator();
                Log.d("Selector : ", "selectedkeys.iterator();");

                while (iterator.hasNext()) {
                    SelectionKey key = (SelectionKey) iterator.next();
                    Log.d("Selector : ", "iterator hasNext");
                    if (key.isAcceptable()) {
                        th.showToast("Accepted succefuuly ",1000);

                        SocketChannel client = server.accept();
                        if (client != null) {
                            client.configureBlocking(false);
                            client.register(selector, SelectionKey.OP_READ);
                            bufferByteSize = ByteBuffer.allocate(1024);
                            client.read(bufferByteSize);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
                            String currentDate = sdf.format(new Date());
                            fileRecieved = new File(Environment.getExternalStorageDirectory(), photoDir+"/new_"+ currentDate+".jpg");
                            fos = new FileOutputStream(fileRecieved);
                            bos = new BufferedOutputStream(fos);

                            bufferByte = ByteBuffer.allocate(bufferByteSize.getInt());
                            client.read(bufferByte);
                            byte [] recevedData = new byte[bufferByteSize.getInt()];
                            bufferByte.get(recevedData);
                            bos.write(recevedData);
                            bos.flush();
                            bufferByteSize.clear();
                            bufferByte.clear();
                            if (client!= null) client.close();
                            int NotifID = 001;

                            Intent i = new Intent(cx, NotificationClass.class);
                            i.putExtra("NotifID", NotifID);
                            displayMyNotification mnotifyMe = new displayMyNotification(i, playMe, cx.getResources(), cx, NotifID);
                            mnotifyMe.start();
                        }

                        InputStreamReader(socket.getInputStream());
                    }
                }
            }
        } catch (Exception e) {
            th.showToast("Error" + e.getMessage().toString(),1000);
        }
        finally {
            if (fos != null) try {
                fos.close();
            } catch (IOException e) {
                th.showToast("Error" + e.getMessage().toString(),1000);
            }
            if (bos != null) try {
                bos.close();
            } catch (IOException e) {
                th.showToast("Error" + e.getMessage().toString(),1000);
            }
        }
    }
}

我在PC上用Java编写了这段代码:

import com.sun.corba.se.spi.oa.OADefault;
import com.sun.xml.internal.stream.util.BufferAllocator;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Scanner;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import sun.java2d.pipe.BufferedBufImgOps;

/**
 *
 * @author laptop home
 */

public class Client {

    public static void main(String args[]) throws IOException {
        Socket  s = null;
        File file_to_send = null;
        byte [] bytes_to_send = null;
        FileInputStream  fis = null;
        BufferedInputStream bis = null;
        OutputStream os = null;

        try {

            file_to_send = new File("C:\\Users\\laptop home\\Desktop\\yblutooth\\secureSyS\\lightbulb-png-825.png");
            bytes_to_send = new byte [(int)file_to_send.length()];
            fis = new FileInputStream(file_to_send);
            bis = new BufferedInputStream(fis);
            bis.read(bytes_to_send, 0, bytes_to_send.length);
            s =  new Socket("192.168.3.100", 5050);
            System.out.println(s.toString());
            Scanner sc = new Scanner(System.in);
            System.out.print("Send File "+file_to_send.getPath().toString()+"??");
            sc.next();
            os =  s.getOutputStream();
            os.write(bytes_to_send.length);
            os.flush();
            os.write(bytes_to_send, 0, bytes_to_send.length);
            os.flush();
        }
        catch (Exception e ) {
            System.out.println(e);
        }
        finally{
            if (s!=null){
                s.close();
            }
        }
    }
}

我想将PC上的Java程序中的照片发送到Android程序。当我启动Android应用程序并运行该线程时,没有任何反应(等待新频道准备就绪)。

当我在PC上启动Java程序时,它告诉我它已与电话成功连接,并在此处打印提示:

System.out.print("Send File "+file_to_send.getPath().toString()+"??");

当我输入任何文本并按 Enter 时,程序将以绿色提示"Build Successfull...etc"结束,没有错误。

我去检查文件夹" RecievedPhotoes",但没有任何东西!

任何人都可以告诉我这是什么问题吗?

0 个答案:

没有答案