Android套接字编程发送多个图像

时间:2018-09-04 12:03:49

标签: android image sockets

我开发了一个项目,当客户端与客户端连接时,服务器正在向客户端发送图像。

我想将所有可用图像发送到特定文件夹。但是发送完一个图像套接字后,它会自动关闭,并且异常。

服务器端代码。

public class ServerLargeImage {

    public String folderPath;

    static Activity activity;

    private static ServerLargeImage m_instance;

    public ServerLargeImage() {
        m_instance = this;
    }

    public static ServerLargeImage instance() {
        if (m_instance == null) {
            m_instance = new ServerLargeImage();


        }
        return m_instance;
    }


    static final int SocketServerPORT = 8080;

    ServerSocket serverSocket;

    ServerSocketThread serverSocketThread;


    public void startSocket(Activity activity) {
        this.activity = activity;
        serverSocketThread = new ServerSocketThread();
        serverSocketThread.start();
    }


    /**
     * @return IP address of Device
     */
    public String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                        .nextElement();
                Enumeration<InetAddress> enumInetAddress = networkInterface
                        .getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress.nextElement();

                    if (inetAddress.isSiteLocalAddress()) {
                        ip += ""
                                + inetAddress.getHostAddress() + "\n";
                    }

                }

            }

        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ip += "Something Wrong! " + e.toString() + "\n";
        }

        return ip;
    }

    /**
     * We are using this method to update current folder path
     *
     * @param folderPath: Folder path of images
     */
    public void updateFolderPath(String folderPath) {
        this.folderPath = folderPath;
    }

    public class ServerSocketThread extends Thread {

        @Override
        public void run() {
            Socket socket = null;

            try {
                serverSocket = new ServerSocket(SocketServerPORT);
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Log.e("ServerLargeImage", "I'm waiting here: "
                                + serverSocket.getLocalPort());
                    }
                });

                while (true) {

                    socket = serverSocket.accept();

                    FileTxThread fileTxThread = new FileTxThread(socket);
                    fileTxThread.start();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }

    }





    public class FileTxThread extends Thread {
        Socket socket;
        long currentTime;

        FileTxThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {

            //Folder path and all file path inside that
            File file = new File(Environment.getExternalStorageDirectory(), folderPath);
            File[] pictures = file.listFiles();


            //send first image to client
             sendAllImageToClient(pictures, 0);


        }

        public void sendAllImageToClient(File[] pictures, int currentIndex) {


            //Current time when the process start
            currentTime = System.currentTimeMillis();

            if (socket.isClosed()) {
                try {
                    socket = serverSocket.accept();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //Calculating size of file and preparing byte array of same size
            byte[] bytes = new byte[(int) pictures[currentIndex].length()];

            //Sending image file with Buffered Input Stream
            BufferedInputStream bis;
            try {
                bis = new BufferedInputStream(new FileInputStream(pictures[currentIndex]));
                bis.read(bytes, 0, bytes.length);

                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                oos.writeObject(bytes);
                // oos.flush();

                final String sentMsg = "File sent to: " + socket.getInetAddress();
                // socket.close();


                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(activity,
                                sentMsg,
                                Toast.LENGTH_LONG).show();
                    }
                });

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            //Print time difference of sending each image
            Log.e("time difference", currentIndex + " " + (System.currentTimeMillis() - currentTime) / 1000 + " sec");

            //Print size of image
            Log.e("File Size", currentIndex + " " + getFolderSizeLabel(pictures[currentIndex]));

            /**
             * Send Next image to client server
             */
            if ((currentIndex + 1) < pictures.length) {
                sendAllImageToClient(pictures , ++currentIndex);
            }

        }
    }

    /**
     * @param file: File path
     * @return
     */
    public static String getFolderSizeLabel(File file) {
        long size = getFolderSize(file) / 1024; // Get size and convert bytes into Kb.
        if (size >= 1024) {
            return (size / 1024) + " Mb";
        } else {
            return size + " Kb";
        }
    }

    /**
     * @param file : File path
     * @return : Size of folder and inner files
     */
    public static long getFolderSize(File file) {
        long size = 0;
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                size += getFolderSize(child);
            }
        } else {
            size = file.length();
        }
        return size;
    }

    /**
     * You can use this method to stop socket while closing your application
     */
    public void onDestroy() {


        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

//客户端代码

public class ClientLargeImage {

static Activity activity;

private static ClientLargeImage m_instance;

public ClientLargeImage() {
    m_instance = this;
}

public static ClientLargeImage instance() {
    if (m_instance == null) {
        m_instance = new ClientLargeImage();


    }
    return m_instance;
}

static final int SocketServerPORT = 8080;


public void connect(Activity activity, String ip_address) {
    this.activity = activity;
    ClientRxThread clientRxThread =
            new ClientRxThread(
                    ip_address,
                    SocketServerPORT);

    clientRxThread.start();
}

private class ClientRxThread extends Thread {
    String dstAddress;
    int dstPort;

    ClientRxThread(String address, int port) {
        dstAddress = address;
        dstPort = port;
    }

    @Override
    public void run() {
        Socket socket = null;

        try {
            socket = new Socket(dstAddress, dstPort);

            File file = new File(
                    Environment.getExternalStorageDirectory(),
                    "/Test");

            if(!file.exists()){
                file.mkdir();
            }

            ObjectInputStream ois = new 
 ObjectInputStream(socket.getInputStream());
            byte[] bytes;
            FileOutputStream fos = null;
            try {
                bytes = (byte[]) ois.readObject();
                long time= System.currentTimeMillis();
                fos = new FileOutputStream(file+"/"+time+".png");
                fos.write(bytes);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (fos != null) {
                   // fos.close();
                }

            }

           // socket.close();

            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(activity,
                            "Finished",
                            Toast.LENGTH_LONG).show();
                }
            });

        } catch (IOException e) {

            e.printStackTrace();

            final String eMsg = "Something wrong: " + e.getMessage();
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(activity,
                            eMsg,
                            Toast.LENGTH_LONG).show();
                }
            });

        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

}

请检查您是否了解套接字编程。

0 个答案:

没有答案