我正在使用远程桌面应用程序,因为我需要将屏幕截图从桌面发送到Android手机。屏幕截图正在创建,我猜也可以在DataOutputstrean上编写,但在客户端,它无法正确读取。以下是代码:
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.imageio.ImageIO;
public class Main {
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();
}
}
}
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.
我被困在这2天了,从stackoverflow尝试了这个代码(链接:ANDROID - Send a screenshot from java to android via tcp socket) 我也得到了同样的错误,但提到的答案没有用,或者我错误地实施了它。
答案 0 :(得分:1)
您有几个设计错误:
不要同时使用BufferedWriter
和DataOutputStream
通过套接字发送/接收数据,如果要发送字符串,可以使用DataOutpurStream
{{ 1}}方法。
在另一个线程上执行读取(从套接字),因为此代码writeUTF(aString)
将阻塞,直到套接字关闭。
在客户端代码中,您正在UI线程上运行套接字通信,这将阻止您的应用程序,为此创建另一个线程。
因为您正在使用以下内容而耗尽内存:
while((n = inStream.read(buffer)) != -1)
其中只从流中读取一个字节并将4096写入文件。而不是 while((n = inStream.read()) != -1) {
content.write(buffer, 0, n);
...
}
使用read()