Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将图像从Java服务器发送到android客户端_Java_Android_Image_Screenshot_Tcpsocket - Fatal编程技术网

将图像从Java服务器发送到android客户端

将图像从Java服务器发送到android客户端,java,android,image,screenshot,tcpsocket,Java,Android,Image,Screenshot,Tcpsocket,我正在编写一个远程桌面应用程序,为此我需要将屏幕截图从桌面发送到android手机。屏幕截图正在创建中,我想它也可以在DataOutputstrean上写入,但在客户端它无法正确读取。代码如下: Server.java: 公共班机{ private static BufferedImage screenshot; private static Robot robot; private static BufferedWriter outToClient; private static FileIn

我正在编写一个远程桌面应用程序,为此我需要将屏幕截图从桌面发送到android手机。屏幕截图正在创建中,我想它也可以在DataOutputstrean上写入,但在客户端它无法正确读取。代码如下:

Server.java: 公共班机{

private static BufferedImage screenshot;
private static Robot robot;
private static BufferedWriter outToClient;
private static FileInputStream inStream;
private static DataOutputStream outStream;
private static int screenWidth;
private static int screenHeight;
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static Thread screenThread;

public static void main(String[] args) {

    try {
        serverSocket = new ServerSocket(21112);  //Server socket

    } catch (IOException e) {
        System.out.println("Could not listen on port: 21111");
    }

    System.out.println("Server started. Listening to the port 21111");

    while (true) {
        try {

            clientSocket = serverSocket.accept();   //accept the client connection
            System.out.println("accepted");
            inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader); //get the client message
            message = bufferedReader.readLine();
            System.out.println(message);

            Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
            robot = new Robot();
            System.out.println("After robot object in thread");
            screenWidth = dimension.width;
            screenHeight = dimension.height;

            Rectangle screen = new Rectangle(screenWidth, screenHeight);

            screenshot = robot.createScreenCapture(screen);
            File file = new File("C:/Users/hp/Desktop/screenshot.png");

            ImageIO.write(screenshot, "jpeg", file);
            System.out.println("After ImageIO.write");

            inStream = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            System.out.println("After Fileinstram");
            // prepare client for receiving the screenshot
            outToClient = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
            outToClient.write("#!<cmd>screenshot");
            System.out.println("After preparing client to read the image file");
            outToClient.newLine();
            outToClient.flush();

            // send the screenshot to the client
            outStream = new DataOutputStream(clientSocket.getOutputStream());
            System.out.println("After Datastream output obj");
            int n;
            int i = 0;

            while((n = inStream.read(buffer)) != -1) {
                System.out.println("In while");
                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();
                outToClient.close();
                clientSocket.close();
            } catch(IOException e) {
                System.out.println(e.getMessage().toString());
            }
        }


            //inputStreamReader.close();
           // clientSocket.close();


    }

}
控制台(服务器):

我在这个问题上被困了2天,尝试了stackoverflow的代码(链接:)
我也会遇到同样的错误,但上面提到的答案不起作用,或者我执行错误。

您有几个设计错误:

不要同时使用
BufferedWriter
DataOutputStream
通过套接字发送/接收数据,如果要发送字符串,可以使用
DataOutputStream
writeUTF(aString)
方法

在另一个线程上执行读取(从套接字),因为此代码
while((n=inStream.read(buffer))!=-1)
将阻塞,直到套接字关闭

在客户端代码中,您正在UI线程上运行套接字通信,这将阻止您的应用程序,为此创建另一个线程

内存不足,因为您正在使用:

 while((n = inStream.read()) != -1) { 

            content.write(buffer, 0, n); 
            ...
 }

它只从流中读取一个字节,并将4096写入文件。使用
read(缓冲区)代替
read()

现在图像将被发送到另一端,但问题是在发送之前在发送方将图像转换为位图类型。我们是否需要在发送之前在位图中转换字节数组,以便在客户端将其解码为图像?您能告诉我如何将字节数组转换为java中的位图吗?在服务器的代码中ange
ImageIO.write(屏幕截图,“jpeg”,文件);
to
ImageIO.write(屏幕截图,“BMP”,文件);
仍然收到相同的错误:D/xxx(27091):在当前状态下:3148854 11-03 02:10:27.793:D/skia(27091):---SkImageDecoder::Factory返回null在Receiver(android客户端)中应该做哪些更改?@user2621826:在发送图像之前和接收图像之后,通过检查图像的大小来确保获得整个图像。我检查过,图像的大小与笔记本电脑上的大小相等,还有什么问题,它仍然会导致上述问题
package roman10.tutorial.tcpcommclient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class TcpClient extends Activity {
    /** Called when the activity is first created. */
    private static Socket s;
    private Handler handler;
    private BufferedReader inFromServer;
    private DataInputStream inStream;
    private ByteArrayOutputStream content;
    private FileOutputStream fileOutStream;
    private final String TAG = "xxx";

private final int SERVER_TRANSFER_PORT = 21115;
@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Log.e("TcpClient" , "in creaste");
    runTcpClient();
   // finish();
}

private static final int TCP_SERVER_PORT = 21115;
private void runTcpClient() {
    try {
         while( true) {
             s = new Socket("10.4.9.169", TCP_SERVER_PORT);
            Log.e("TcpClient" , "socket created");
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            //send output msg

            String outMsg = "TCP connectingfghg to " + System.getProperty("line.separator") ; 
            out.write(outMsg);
            out.flush();
            Log.e("TcpClient", "sent: " + outMsg);

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

            String message = "";
            if((message = inFromServer.readLine()) != null) {
                if(message.equals("#!<cmd>screenshot")) {
                    receiveScreenshot(s);
                }
            }
         }
        /*
        Thread cclientscreen = new Thread(new ClientTransferThread(new Handler()));
        cclientscreen.start();*/
        //accept server response
        //String inMsg = in.readLine() + System.getProperty("line.separator");
        //Log.e("TcpClient", "received: " + inMsg);
        //close connection

    }catch (UnknownHostException e) {
        e.printStackTrace();
    }catch(IOException e) {
        Log.e(TAG, "ClientTransferThread 1: " + e.getMessage().toString());
    } finally {
        try {
            inFromServer.close();
            //s.close();
            //serverTransferSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "ClientTransferThread 2: " + e.getMessage().toString());
        }
    } 
}

 public static Socket getS() {
        return s;
      }

      public static void setS(Socket s) {
        TcpClient.s = s;
    }
    private void receiveScreenshot(Socket socketX) {
        Log.d(TAG, "ClientTransferThread: receiveScreenshot()");

        try {
            Log.d(TAG, "receiveScreenshot(): receiving screenshot");
           // handler.sendMessage(buildMessage("> Receiving screenshot.."));
            inStream = new DataInputStream(socketX.getInputStream());

            Log.d(TAG, "receiveScreenshot(): after datastream");
            byte[] buffer = new byte[4096];
            content = new ByteArrayOutputStream();

            int n;
            while((n = inStream.read()) != -1) { 

                content.write(buffer, 0, n); 
                Log.d(TAG, "rcvscrnshot: in while");// HERE I "OUT OF MEMORY"
                content.flush();
            }

            Log.d(TAG, "rcvscrnshot: outside while");
           // File directory = new File(ServerActivity.APP_FOLDER_PATH);
            //File screenshot = new File(Environment.getExternalStorageState()  + "/" + "screenshot.png");
            String path = "/storage/sdcard/picshello";
            File outputDir= new File(path); 

            Log.d(TAG, "rcvscrnshot: after outfilepath dir");

            outputDir.mkdirs();
            Log.d(TAG, "rcvscrnshot: mkdir");
            File screenshot = new File(path+"/"+"screenshot.jpeg");
            Log.d(TAG, "rcvscrnshot: opening png file");
           // FileOutputStream out = new FileOutputStream(screenshot);   
            //bmp.compress(Bitmap.CompressFormat.PNG, 100, out);   
//          if(!directory.exists())
//              directory.mkdirs();
/*
            if(!screenshot.exists()) {
                screenshot.createNewFile();
            }
            else {
                screenshot.delete();
                screenshot.createNewFile();
            }
*/
            Log.d(TAG, "rcvscrnshot: file created");
            fileOutStream = new FileOutputStream(screenshot);
            Log.d(TAG, "rcvscrnshot: fileoutstream");
            Bitmap bmp = BitmapFactory.decodeByteArray(content.toByteArray(), 0, content.size());
            Log.d(TAG, "rcvscrnshot: bmp created");
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutStream);
            Log.d(TAG, "rcvscrnshot: bmp compressed");

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

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

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

        Message msg = handler.obtainMessage();
        Bundle bundle = new Bundle();
        bundle.putString("MESSAGE", text);
        msg.setData(bundle);
        return msg;
    }
    /*
    //replace runTcpClient() at onCreate with this method if you want to run tcp client as a    service
    private void runTcpClientAsService() {
        Intent lIntent = new Intent(this.getApplicationContext(), TcpClientService.class);
        this.startService(lIntent);
    }
    */
}
... // After creating socket it prints "in while" many times
11-03 00:11:05.373: D/xxx(7134): rcvscrnshot: in while
11-03 00:11:05.373: D/xxx(7134): rcvscrnshot: in while
11-03 00:11:05.373: D/xxx(7134): rcvscrnshot: outside while
11-03 00:11:05.373: D/xxx(7134): rcvscrnshot: after outfilepath dir
11-03 00:11:05.373: D/xxx(7134): rcvscrnshot: mkdir
11-03 00:11:05.373: D/xxx(7134): rcvscrnshot: opening jpeg file
11-03 00:11:05.373: D/xxx(7134): rcvscrnshot: file created
11-03 00:11:05.373: D/xxx(7134): rcvscrnshot: fileoutstream
11-03 00:11:05.453: D/dalvikvm(7134): GC_FOR_ALLOC freed 825K, 43% free 11154K/19452K, paused 80ms, total 80ms
11-03 00:11:05.573: I/dalvikvm-heap(7134): Grow heap (frag case) to 18.806MB for 8222931-byte allocation
11-03 00:11:05.673: D/dalvikvm(7134): GC_FOR_ALLOC freed 0K, 31% free 19185K/27484K, paused 80ms, total 80ms
11-03 00:11:05.693: D/skia(7134): --- SkImageDecoder::Factory returned null
11-03 00:11:05.693: D/xxx(7134): rcvscrnshot: bmp created
11-03 00:11:05.713: D/AndroidRuntime(7134): Shutting down VM
11-03 00:11:05.713: W/dalvikvm(7134): threadid=1: thread exiting with uncaught exception (group=0xb1a99ba8)
11-03 00:11:05.733: E/AndroidRuntime(7134): FATAL EXCEPTION: main
11-03 00:11:05.733: E/AndroidRuntime(7134): Process: roman10.tutorial.tcpcommclient, PID: 7134
11-03 00:11:05.733: E/AndroidRuntime(7134): java.lang.RuntimeException: Unable to start activity ComponentInfo{roman10.tutorial.tcpcommclient/roman10.tutorial.tcpcommclient.TcpClient}: 
                    java.lang.NullPointerException
11-03 00:11:05.733: E/AndroidRuntime(7134):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
11-03 00:11:05.733: E/AndroidRuntime(7134):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
Server started. Listening to the port 21111
accepted
TCP connectingfghg to 
After robot object in thread
After ImageIO.write
After Fileinstram
After preparing client to read the image file
After Datastream output obj
In while
1. Byte[4096]
In while
..... // Like this till it reads the whole file.
 while((n = inStream.read()) != -1) { 

            content.write(buffer, 0, n); 
            ...
 }