Welcome to fun programming. Here we are creating a socket to a simple http web server. This program is taking screen shot of server system to client request browser. If I wanna see my friend screen and my friend is running this program then I just type his IP:8989 on browser and can see his current screen. Improvement of this program as continuous streaming is home assignment for you. Thanks to Vikram.
Run : Java WebScreen
See in browser type : http://localhost:8989
developed By : GauravDS & Vikram Biwal.
import java.io.*;
import java.net.*;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
class WebScreen {
SimpleDateFormat formatter = new SimpleDateFormat("yyyMMddhhmmssa");
public static void main(String argv[]) throws Exception
{
new WebScreen().showImage();
}
public String robo() throws Exception
{
Calendar now = Calendar.getInstance();
String name = formatter.format(now.getTime());
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(screenShot, "JPG", new File(name +".jpg"));
System.out.println(formatter.format(now.getTime()));
return name+".jpg";
}
public void showImage() throws Exception
{
String clientSentence;
String file1 = "";
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(8989);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
file1 = this.robo();
PrintStream out=new PrintStream(new BufferedOutputStream(
connectionSocket.getOutputStream()));
// read the data sent. We basically ignore it,
// stop reading once a blank line is hit. This
// blank line signals the end of the client HTTP
// headers.
// Send the response
// Send the headers
InputStream f=new FileInputStream(file1);
out.print("HTTP/1.0 200 OK\r\nContent-type: image/jpeg\r\n\r\n");
// Send file contents to client, then close the connection
byte[] a=new byte[8192];
int n;
while ((n=f.read(a))>0)
out.write(a, 0, n);
out.close();
welcomeSocket.close();
TCPServer obj = new TCPServer();
obj.showImage();
}
}
}
Compile : Javac WebScreen.java Run : Java WebScreen
See in browser type : http://localhost:8989
developed By : GauravDS & Vikram Biwal.
No comments:
Post a Comment