Saturday 27 February 2016

How to communicate with browser using Java Socket Program ?


import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketTest {
public static void main(String args[])throws Exception{
  ServerSocket serverSocket = null;
       try {
             serverSocket = new ServerSocket(8083);
           } catch (IOException e)
           {
             System.err.println("Could not listen on port: 8083.");
             System.exit(1);
       }

       Socket clientSocket = null;
       try {
            clientSocket = serverSocket.accept();

            if(clientSocket != null)              
                System.out.println("Connected");

       } catch (IOException e) {
             System.err.println("Accept failed.");
             System.exit(1);
      }

     PrintWriter out = new PrintWriter(clientSocket.getOutputStream());


    out.println("HTTP/1.1 200 OK");
    out.println("Content-Type: text/html");
    out.println("\r\n");
    out.println("<html> <head/> <body> <p> Hello world </p> </body> </html>");
    out.flush();

    out.close();

    clientSocket.close();
    serverSocket.close();
}

}



Compile the code and run it in console using java command..
Enter url in browser is....http://localhost:8083 

It will show output like..

No comments:

Post a Comment