ANDROID - 通过tcp socket将截图从java发送到android

时间:2012-08-20 17:08:41

标签: java android image sockets tcp

我通过套接字进行了客户端 - 服务器聊天,效果很好。现在我想为服务器(Android手机)添加一个选项来从客户端(pc应用程序)抓取屏幕截图。创建屏幕截图工作正常,但每次从客户端到服务器的传输都失败。

CLIENT-SIDE / SENDER:

在我将图像直接写入输出流之前,我在服务器端出错,所以我尝试了这种方式,但它也是一样的。

public class ClientScreenshotThread implements Runnable {

// - Software Init - //
private Socket transferSocket;
private BufferedImage screenshot;
private Robot robot;
private BufferedWriter outToServer;
private FileInputStream inStream;
private DataOutputStream outStream;

// - Var Init - //
private final int SERVER_TRANSFER_PORT = 65000;

private int screenWidth, screenHeight;

// -------------------------------------------------- //

public ClientScreenshotThread() {

}

@Override
public void run() {
    try {
        SocketAddress sockaddr = new InetSocketAddress(Client.SERVER_IP, SERVER_TRANSFER_PORT);
        transferSocket = new Socket();
        transferSocket.connect(sockaddr, 5000);     // 5sec Timeout

        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        robot = new Robot();

        screenWidth = dimension.width;
        screenHeight = dimension.height;

        Rectangle screen = new Rectangle(screenWidth, screenHeight);

        screenshot = robot.createScreenCapture(screen);
        ImageIO.write(screenshot, "png", new File("/Users/chris/Downloads/screenshot.png"));

        File file = new File("/Users/chris/Downloads/screenshot.png");
        inStream = new FileInputStream(file);
        byte[] buffer = new byte[4096];

        // prepare server for receiving the screenshot
        outToServer = new BufferedWriter(new OutputStreamWriter(transferSocket.getOutputStream()));
        outToServer.write("#!<cmd>screenshot");
        outToServer.newLine();
        outToServer.flush();

        // send the screenshot to the server
        outStream = new DataOutputStream(transferSocket.getOutputStream());

        int n;
        int i = 0;
        while((n = inStream.read(buffer)) != -1) {
            i++;
            System.out.println(i + ". Byte[" + n + "]");
            outStream.write(buffer, 0, n);
            outStream.flush();
        }

    } catch(AWTException e1) {
        System.out.println("AWT: " + e1.getMessage().toString());
    } catch(IOException e2) {
        System.out.println("IO: " + e2.getMessage().toString());
    } finally {
        try {
            // close streams and socket
            inStream.close();
            outToServer.close();
            transferSocket.close();
        } catch(IOException e) {
            System.out.println(e.getMessage().toString());
        }
    }
}
}

服务器端/接收器:

我总是在:

获得“NullPointerException”

bmp.compress(Bitmap.CompressFormat.PNG,100,fileOutStream);

public class ServerTransferThread implements Runnable {

// - Software Init - //
private ServerSocket serverTransferSocket;
private Handler handler;
private BufferedReader inFromClient;
private DataInputStream inStream;
private ByteArrayOutputStream content;
private FileOutputStream fileOutStream;

// - Var Init - //
private final String TAG = "xxx";

private final int SERVER_TRANSFER_PORT = 65000;

// -------------------------------------------------- //

public ServerTransferThread(Handler _handler) {
    this.handler = _handler;
}

@Override
public void run() {
    Log.d(TAG, "ServerTransferThread: run()");

    try {
        serverTransferSocket = new ServerSocket(SERVER_TRANSFER_PORT);

        while(ServerActivity.SERVER_STATE == true) {
            Socket socket = serverTransferSocket.accept();
            Log.d(TAG, "ServerTransferThread: accepted()");

            inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            Log.d(TAG, "ServerTransferThread: bufferedReader()");

            String message = "";
            if((message = inFromClient.readLine()) != null) {
                if(message.equals("#!<cmd>screenshot")) {
                    receiveScreenshot(socket);
                }
            }
        }
    } catch(IOException e) {
        Log.e(TAG, "ServerTransferThread 1: " + e.getMessage().toString());
    } finally {
        try {
            inFromClient.close();
            serverTransferSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "ServerTransferThread 2: " + e.getMessage().toString());
        }
    }
}

private void receiveScreenshot(Socket socketX) {
    Log.d(TAG, "ServerTransferThread: receiveScreenshot()");

    try {
        handler.sendMessage(buildMessage("> Receiving screenshot.."));
        inStream = new DataInputStream(socketX.getInputStream());

        byte[] buffer = new byte[4096];
        content = new ByteArrayOutputStream();

        inStream = new DataInputStream(socketX.getInputStream());

        int n;
        while((n = inStream.read()) != -1) {     
            content.write(buffer, 0, n);     // HERE I "OUT OF MEMORY"
            content.flush();
        }

        File directory = new File(ServerActivity.APP_FOLDER_PATH);
        File screenshot = new File(ServerActivity.APP_FOLDER_PATH + "/" + "screenshot.png");

        if(!directory.exists())
            directory.mkdirs();

        if(!screenshot.exists()) {
            screenshot.createNewFile();
        }
        else {
            screenshot.delete();
            screenshot.createNewFile();
        }

        fileOutStream = new FileOutputStream(screenshot);
        Bitmap bmp = BitmapFactory.decodeByteArray(content.toByteArray(), 0, content.size());
        bmp.compress(Bitmap.CompressFormat.PNG, 100, fileOutStream);

        handler.sendMessage(buildMessage("> Screenshot received sucessfully!"));

    } catch(IOException e1) {
        Log.e(TAG, "ServerTransferThread 3: " + e1.getMessage().toString());
    } finally {
        try {
            inStream.close();
            content.close();
            fileOutStream.close();
            socketX.close();
        } catch (IOException e) {
            Log.e(TAG, "ServerTransferThread 4: " + e.getMessage().toString());
        }
    }
}

private Message buildMessage(String text) {
    Log.d(TAG, "ServerTransferThread: buildMessage()");

    Message msg = handler.obtainMessage();
    Bundle bundle = new Bundle();
    bundle.putString("MESSAGE", text);
    msg.setData(bundle);
    return msg;
}

这是我的Logcat输出:

08-20 19:01:18.285: D/skia(5383): --- SkImageDecoder::Factory returned null
08-20 19:01:18.295: W/dalvikvm(5383): threadid=12: thread exiting with uncaught exception (group=0x40c6b1f8)
08-20 19:01:18.295: E/AndroidRuntime(5383): FATAL EXCEPTION: Thread-3051
08-20 19:01:18.295: E/AndroidRuntime(5383): java.lang.NullPointerException
08-20 19:01:18.295: E/AndroidRuntime(5383):     at net.api.speak.wifi.ServerTransferThread.receiveScreenshot(ServerTransferThread.java:114)
08-20 19:01:18.295: E/AndroidRuntime(5383):     at net.api.speak.wifi.ServerTransferThread.run(ServerTransferThread.java:58)
08-20 19:01:18.295: E/AndroidRuntime(5383):     at java.lang.Thread.run(Thread.java:856)
08-20 19:01:27.820: D/Speak WiFi(5383): Server: onDestroy()
08-20 19:01:27.830: E/Speak WiFi(5383): Server: Socket closed
08-20 19:01:27.830: E/Speak WiFi(5383): ServerThread: Socket closed

编辑:遇到麻烦后,我找到了文件传输问题的最终解决方案!那是:


最终服务器端:

            int bytecount = 2048;
            byte[] buf = new byte[bytecount];

            OutputStream OUT = socket.getOutputStream();
            BufferedOutputStream BuffOUT = new BufferedOutputStream(OUT, bytecount);
            FileInputStream in = new FileInputStream(itemPath);

            int i = 0;
            while ((i = in.read(buf, 0, bytecount)) != -1) {
                BuffOUT.write(buf, 0, i);
                BuffOUT.flush();
            }

最终客户端:

        FileOutputStream outToFile = new FileOutputStream(FileName);

        int bytecount = 2048;
        byte[] buf = new byte[bytecount];

        // Create an inputstream for the file data to arrive
        InputStream IN = socket.getInputStream();
        BufferedInputStream BuffIN = new BufferedInputStream(IN, bytecount);

        // Receiving file..
        int i = 0;
        int filelength = 0;       
        while((i = BuffIN.read(buf, 0, bytecount)) != -1) {
            filelength += i;
            outToFile.write(buf, 0, i);
            outToFile.flush();
        }

2 个答案:

答案 0 :(得分:0)

您是否可以将收到的字节直接写入FileOutputStream。 在像智能手机这样相当有限的设备上将png转换为位图有时会引起问题。

您是否需要在接收方创建Bitmap对象?

如果没有,你可以这样做:

InputStream is = socketX.getInputStream();
FileOutputStream outputFile = new FileOutputStream(screenshot);

int n;
while ((n = is.read(data, 0, data.length)) != -1) {
  outputFile.write(data, 0, n);
}

我还没有测试过代码。

答案 1 :(得分:0)

NullPointerException是因为BitmapFactory.decodeByteArray返回:已解码的位图,如果图像无法解码,则返回null。

服务器端(在receiveScreenshot()方法内),将InputStream字节写入ByteArrayOutputStream'content'变量的部分不正确,因为inStream.read()应为inStream.read(buffer)

可以解释Out of Memory错误,因为read()方法一次只读取一个字节,然后对于每个字节,总是写一个4096字节的完整缓冲区。

编辑:一旦你编写了fileOutputStream中的所有字节,并且你不想直接提供字节(因为在你的情况下,它是什么没有),将OutputStream压缩为png工作):

// Write bytes inside fileOutStream

Bitmap bmp = BitmapFactory.decodeFile(screenshot.getAbsolutePath());
bmp.compress(Bitmap.CompressFormat.PNG, 100, fileOutStream);
fileOutStream.close();

这应该可以满足您的需求,但是因为你应该已经知道里面的字节所以很难解码文件。