我正在尝试显示我使用 screenCapture 从服务器端获取的图像,但在客户端(Android 模拟器)上通过异常“OutOfMemoryException”运行一段时间后不显示任何图像。所以我需要一些帮助。这是代码。
服务器
public class Server
{
private Connection con;
private ScreenCapture sp;
private Socket soc;
private DataOutputStream out;
private DataInputStream in;
public Server() throws IOException, AWTException
{
con = new Connection();
sp = new ScreenCapture();
}
public void init() throws IOException, AWTException
{
con.setPort(3838);
ServerSocket serversocket = new ServerSocket(3838);
soc = serversocket.accept();
System.out.println("Accepted");
out = new DataOutputStream(soc.getOutputStream());
in = new DataInputStream(soc.getInputStream());
while(true)
{
sp.CreateScreenCapture();
out.write(sp.getScreenCapture());
}
}
public void closeConnection() throws IOException
{
soc.close();
}
public static void main(String[] arg)
{
Server server = null;
while(true)
{
try
{
server = new Server();
server.init();
}
catch (IOException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
catch (AWTException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
try
{
server.closeConnection();
}
catch (IOException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
客户
public class UpdateScreen extends View
{
private DataInputStream input;
private DataOutputStream output;
private Socket soc;
private Bitmap image;
public UpdateScreen(Context context) throws UnknownHostException, IOException
{
super(context);
// TODO Auto-generated constructor stub
this.setFocusable(true);
this.setFocusableInTouchMode(true);
init();
}
public void init() throws UnknownHostException, IOException
{
soc = new Socket(InetAddress.getByName("10.0.2.2"), 3838);
input = new DataInputStream(soc.getInputStream());
while(true)
{
byte[] img = this.getByteArrayFromStream();
image = BitmapFactory.decodeByteArray(img, 0, img.length);
}
}
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
// TODO Auto-generated method stub
image = Bitmap.createScaledBitmap(image, w, h, false);
}
public byte[] getByteArrayFromStream() throws IOException
{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nread;
byte[] data = new byte[1042];
while((nread = input.read(data, 0, data.length)) != -1)
{
buffer.write(data, 0, nread);
}
return buffer.toByteArray();
}
@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
invalidate();
super.onDraw(canvas);
canvas.drawBitmap(image, 0, 0, null);
}
}