Servidor Web exportando imagens em java

0 respostas
H

Olá pessoal,

a pouco tempo estive estudando sobre servidores de streaming em java
Tanto que acabei encontrando o Red5 http://osflash.org/red5 e o Milenia Grafter http://milgra.com/
Bem, o red5 foi muito complicado e até deixei de lado, já o Milgra é bem enxuto mas não consegui faze-lo funciona, por falta de documentação.
Se alguém souber ou que já tenha feito, por favor a ajuda será muito bem vinda.
Enfim, como não consegui montar o servidor streaming.
E de tanto pensar sobre o assunto, acabei tendo uma ideia bem simples:
Montar um servidor web em conjunto com a captura do desktop e publicar isso para um cliente http sem a necessidade de plugin ou qualquer outro apetrecho adicional.
E foi exatamente o que fiz e até que ficou bem simples, mais do que eu esperava +/- 150 linhas.
O fonte está logo abaixo:
Por padrão ele abre a porta 80 e o cliente atualiza a tela requerindo uma nova requisição de 10 em 10 segundos
Caso queira variar, basta passar os parâmetros para o servidor

java HttpScreenServer 80 10

O primeiro é a porta e o segundo o intervalo de atualização em segundos

Depois de executar o servidor e a porta for aberta sem maiores problemas.
Abra o firefox ou o ie e acesse o servidor, se vc testando localmente digite o endereço: http://127.0.0.1:80 ou http://localhost:80 e confira o resultado
Ah… detalhe o ideal seria o servidor em um máquina separada e o cliente em outra recebendo as requisições.
Se houver alguma dica ou melhoria, fiquem livres para comentar.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;

public class HttpScreenServer extends Thread {
	private Socket in;
	private int counter, timeout ;

	public HttpScreenServer(Socket income, int c, int tout) {
		in = income;
		counter = c;
		timeout = tout;
	}
	/**
	 * run da thread
	 */
	public void run() {
		String from, localhost, body, body2, spbody, request = new String();

		BufferedReader br = null;
		OutputStream out = null;

		try {
			String username = System.getProperty("user.name");

			from = in.getInetAddress().toString();
			localhost = InetAddress.getLocalHost().toString();
			System.out.print("\rThread number : " + counter);
			System.out.print("\rAccessed from : " + from + " ; Username : " + username);

			out = in.getOutputStream();
			br = new BufferedReader(new InputStreamReader(in.getInputStream()));

			while (br.ready())
				request = request + br.readLine() + "\n";

			System.out.print("\r" + request);

			if (request.startsWith("GET / ")) {
				body = "HTTP/1.1 200 OK" + "\nMIME-Version: 1.0"
						+ "\nServer: ScreenServer/JAVA 0.2"
						+ "\nLast-Modified: 14 Nov 1997 09:02:00 GMT"
						+ "\nContent-type: text/html" + "\nContent-Length: ";
				body2 = "<TITLE>User: " + username 
				        + " - Localhost: " + localhost 
				        + " - From : " + from 
				        + " [" + counter + "]</TITLE>";
				body2 += "<META HTTP-EQUIV=Refresh CONTENT=" + timeout	+ ">"
				        /* + "<SCRIPT>setTimeout('location.reload(true)'," + (timeout*1000)+ ")</SCRIPT>" */ //usando javascript
				        + "<BODY topmargin=0 leftmargin=0><IMG SRC='img.png'></BODY>";
				spbody = "\n\n";
				body = body + Long.toString(body2.length()) + spbody;

				out.write(body.getBytes());
				out.write(body2.getBytes());
			} else if (request.startsWith("GET /img")) {
				ByteArrayOutputStream baos = captureScreenToFile();

				body = "HTTP/1.1 200 OK" + "\nMIME-Version: 1.0"
						+ "\nServer: ScreenServer/JAVA 0.2"
						+ "\nContent-type: image/png" + "\nContent-Length: ";
				body = body + Long.toString(baos.size()) + "\n\n";

				out.write(body.getBytes());
				out.write(baos.toByteArray());
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			try { br.close(); } catch (IOException e) {}
			try { out.close(); } catch (IOException e) {}
			try { in.close(); } catch (IOException e) {}

		}
		System.out.print("\rClosed Thread number : " + counter);
	}
	/**
	 * Captura tela, convertendo a imagem em PNG e retornando um arranjo de bytes
	 * @return
	 * @throws IOException
	 * @throws HeadlessException
	 * @throws AWTException
	 */
	private synchronized ByteArrayOutputStream captureScreenToFile()throws IOException, HeadlessException, AWTException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		BufferedImage bi = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
		drawMouse(bi);
		ImageIO.write(bi, "png", baos);
		return baos;
	}
	/** 
	 * Desenha o ponteiro do mouse
	 * @param bi
	 */
	private void drawMouse(BufferedImage bi) {
		Graphics2D g2 = bi.createGraphics();
		Point p = MouseInfo.getPointerInfo().getLocation();
		g2.drawRect(p.x, p.y, 5, 5);
	}

	/**
	 * Ponto de entrada
	 * @param args
	 */
	public static void main(String[] args) {
		int i = 1, port = 80, timeout = 10;
		
		if( args.length == 0)
		System.out.println("Modo de uso: " 
						 + "\n\njava HttpServerScreen [port] [timeout] "
				         + "\n\nport    : porta http aberta (padrao 80)"
				         + "\ntimeout : tempo em segundos que o cliente atualizara (padrao 10)");
		else {
			port = Integer.parseInt(args[0]);
			if( args.length == 2)
			timeout = Integer.parseInt(args[1]);
		}
		
		try {
			ServerSocket s = new ServerSocket(port);
			System.out.println("----------------"
					         + "\nHttpServerScreen esta rodando na porta " + port + " e atualizara a cada " + timeout + " segundos." 
					         + "\n----------------");
			while (true) {
				Socket income = s.accept();

				new HttpScreenServer(income, i, timeout).start();

				i = (i == Integer.MAX_VALUE) ? 1 : i + 1;
			}// of while
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

[]'s
Humberto Lino.

Criado 27 de dezembro de 2008
Respostas 0
Participantes 1