⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 simplewebserver1.java

📁 一个Web服务器测试程序
💻 JAVA
字号:
//Copyright 2001 by Ted Kosan, Version 1.0.1
//This class implements a simple HTTP web server that serves a small default
// HTML file when it receives an HTTP GET request.  The server makes its
// service available on port 8080 of the machine it is running on.

package webtest;

import java.io.*;
import java.net.*;

//This class places an http server on port 8080 and waits for http requests.
public class SimpleWebServer1
{

  private InetAddress serverAddress;
  private String serverIP;
  private ServerSocket serverSocket;
  private Socket clientSocket;
  private String httpCommand;
  private StringBuffer htmlBuffer;
  private StringBuffer headerBuffer;
  private int hitCount = 0;
  private int portNumber;

  //This constructor take the port to place the server on.
  public SimpleWebServer1(int portNum)
  {
    super();
    this.portNumber = portNum;
  }

  public void startWebServer()
  {

    //Get the IP address of this machine and print it to standard out.
    try
    {
      InetAddress serverAddress = InetAddress.getLocalHost();

      serverIP = serverAddress.toString();
      serverIP = serverIP.substring(serverIP.indexOf('/')+1);

    }//end try.
    catch (IOException ioe)
    {
      System.out.println("Unknown local host: " + ioe);
      System.exit(0);
    }//end catch.


    //Open a server socket on the specified port and wait for an HTTP request.
    // When an HTTP request is received it is handled by the handleClientRequest
    // method.
    try
    {
      //Instantiate a ServerSocket object and attach it to the specified port.
      serverSocket = new ServerSocket(portNumber, 10);

      //Let the server administrator know what the IP address of the server's
      // machine is along with what port it is listening on.
      System.out.println("\nStarting server on " + serverIP + ":" + portNumber);

      //This loop continuously waits for socket connections attaching themselves
      // to port 8080 and when a socket connection has been made the client's
      // request will be handled by the handleClientRequest method.
      while (true)
      {
        //This method waits (blocks) for a socket connection and when it
        // receives one it passes it back as a Socket object.
        clientSocket = serverSocket.accept();

        //Service the client's request.
        handleClientRequest(clientSocket);

      }

      //If the above while loop was not an infinite loop then we would need to
      // uncomment the follow line in order to close the socket connection
      // after we were done with it.
        //serverSocket.close();

    }//end try.
    catch (IOException ioe)
    {
      System.out.println("Error in SimpleWebServer: " + ioe);
      ioe.printStackTrace();
    }//end catch.

  }//end method


  //This method discovers what the client wants and handles their request.
  private void handleClientRequest(Socket client) throws IOException
    {
      BufferedReader inputStream = null;
      OutputStream outputStream = null;
      String inputLine;
      StringBuffer htmlResponse;

      try
      {
        // Acquire the streams for IO.
        inputStream = new BufferedReader( new InputStreamReader(client.getInputStream()) );

        boolean firstLine = true;
        while((inputLine = inputStream.readLine()) != null && inputLine.compareTo("") != 0)
        {
          if (firstLine)
          {
            httpCommand = inputLine;
            firstLine = false;
          }

          //Print each line as it is received to standard out.
          System.out.println(inputLine);

        }//end while.


        //If the HTTP command was a GET request then send back the default HTML
        // response.  If the command was not GET then simply close the
        // connection.
        if (httpCommand.startsWith("GET") || httpCommand.startsWith("get"))
        {
          //Output response to browser.
          System.out.println("Outputting response to GET request.");

          //Have the prepareHTMLResponse helper method assemble the default HTML
          // web page that we will use as a response and return it to us in a
          // StringBuffer.
          htmlResponse = this.prepareHTMLResponse();

          //Use the Socket to open an output stream back to the client and then
          // send the default web page back to the client using this stream.
          outputStream = client.getOutputStream();
          outputStream.write(htmlResponse.toString().getBytes());

        }//end if.
        else
        {
          System.out.println("Command was not a GET request.");
        }//end else.


      }//end try.
      catch (IOException ioe)
      {
        System.out.println("Error in SimpleWebServer: " + ioe);
        ioe.printStackTrace();
      }//end catch.
      finally
      {
        // Cleanup
        System.out.println("Cleaning up connection: " + client + "\n\n");
        outputStream.close();
        inputStream.close();
        client.close();

      }//end finally.

    }//end method.



    //This method assembles the default HTML page that will be sent back to the
    // client (probably a bowser).
    private StringBuffer prepareHTMLResponse()
    {
      //Clear out the HTML buffer and the HTTP header buffer that will be used
      // to transfer the HTML code over the internet.
      htmlBuffer = new StringBuffer();
      headerBuffer = new StringBuffer();

      // Assemble the HTML page.
      htmlBuffer.append("<HTML>\n");
      htmlBuffer.append("  <HEAD>\n<TITLE>Test HTML Document</TITLE>\n");
      htmlBuffer.append("  </HEAD>\n");
      htmlBuffer.append("         \n");
      htmlBuffer.append("  <BODY>\n");
      htmlBuffer.append("    <h1>This is your Java web server's default page.</h1>");
      htmlBuffer.append("This page has been served " + ++hitCount + " times.");
      htmlBuffer.append("  </BODY>\n");
      htmlBuffer.append("</HTML>\n");

      // Assemble the HTTP response header.
      headerBuffer.append("HTTP/1.0 200 OK\r\n");
      headerBuffer.append("Content-type: text/html\r\n");
      headerBuffer.append("Content-length: " + htmlBuffer.length() );
      headerBuffer.append("\r\n\r\n");

      //Append HTML page to the HTTP response header.
      headerBuffer.append(htmlBuffer.toString());

      // Return the complete response to the code that invoked this method.
      return headerBuffer;
    }

    public static void main(String args[])
    {
      SimpleWebServer1 sws = new SimpleWebServer1(8080);
      sws.startWebServer();
    }

 }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -