6

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

客户端/发件人:

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

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

2 回答 2

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

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

于 2012-08-20T17:26:00.200 回答
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);
}

我没有测试过代码。

于 2012-08-20T17:18:16.570 回答