Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Create a server program that listens on port 8000 using java

This project shows how to create a simple Web server. Create a server program that
listens on port 8000. When a client connects to the server, the program should
send the following data to the client:
“HTTP/1.0 200 OK\n\n” + body
where body is the String “<HTML><TITLE>Java Server</TITLE>This web
page was sent by our simple <B>Java Server</B></HTML>”. If you know
HTML, feel free to insert your own content. The header line identifies the message
as part of the HTTP protocol that is used to transmit Web pages.
When the server is running, you should be able to start a Web browser and
navigate to your machine on port 8000 and view the message. For example, if the
server is running on your local machine, you could point your Web browser to
http://localhost:8000 and the message in body should be displayed.

Answer:



/**
 * Question.java
 *
 * This program implements a simple web server that always transmits the same
 * "web page."   It listens on port 8000 so one must navigate to
 * http://localhost:8000 to access it.
 */
import java.net.ServerSocket;
import java.net.Socket;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Question
{
	public static void main(String[] args)
	{
		try
		{
			System.out.println("Waiting for a connection on port 8000.");
			ServerSocket serverSock = new ServerSocket(8000);
			Socket connectionSock = serverSock.accept();

			BufferedReader clientInput = new BufferedReader(
				new InputStreamReader(connectionSock.getInputStream()));
			DataOutputStream clientOutput = new DataOutputStream(
				connectionSock.getOutputStream());

			System.out.println("Connection made!");
			String body = "<HTML><TITLE>Java Server</TITLE>This web " +
					"page was sent by our simple <B>Java" +
" Server</B></HTML>";
			String replyText = "HTTP/1.0 200 OK\n\n" + body;

			clientOutput.writeBytes(replyText);

			clientOutput.close();
			connectionSock.close();
			serverSock.close();
		}
		catch (IOException e)
		{
			System.out.println(e.getMessage());
		}
	}
} 


About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!