Android的套接字文件传输

Android的套接字文件传输

本文介绍了Android的套接字文件传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要帮助......我已经明白如何使服务器 - 客户端套接字连接如...它的工作原理呸......现在我想从服务器传输文件到客户端和回....这里有我的消息来源..

Need help... I have understood how to make server-client socket conection... It works fie... Now I want to transfer files from server to client and back.... here are my sources...

套接字服务器...

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 ...

Socket Client...

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

件而被标记为///////不工作....帮助

Pieces of source which are marked by "///////" don't work.... Help

推荐答案


更好您替换以下的code


Better you replace the following your code

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

与下面的一个

with the following one

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


那就试试吧。


Then try it

这篇关于Android的套接字文件传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:45