2006/05/08 | [D8]简易网页浏览器及其服务器(85分)
类别(开发) | 评论(2) | 阅读(459) | 发表于 20:49
Exercise 1 of SSD 8 -- JAVA
——85分作业~出了一点小错误~遗憾ing...

[题目要求]实现网络客户端、单/多线程网络服务器的功能。
[关键技术]
[心得体会]
  稍候详细介绍……

本着学术交流的目的和宗旨,欢迎大家的七嘴八舌~

iCarnegie-SSD8-Exercise1原题如下:

[Ctrl+A 全部选择 提示:你可先修改部分代码,再按运行]

其反馈信息如下:

[Ctrl+A 全部选择 提示:你可先修改部分代码,再按运行]


本人编写的程序ReadMe文件如下:
引用:
Readme for Exercise 1 of SSD 8
Here are the instructions on compiling and running each program:
Client.java
First, compile this java file through cmd:
javac Client.java

to Client.class. Second, run this class file also through cmd:
java Client <the address of web server>

Then you can see the guide for input the request if the connection is OK. Now, input the request. For example:
GET / HTTP/1.0

Then the web information will be displayed on the screen and the program will remind you to save the web file. At last, input the file name which you wanna save.
 
Note: If you don't input the address of web server, the program will input an error message on the screen.
 
Server.java
First, compile this java file through cmd:
javac Server.java

to Server.class. Second, run this class file also through cmd:
java Server

Now the server is waiting for request from clients. When a client connecting with it, it will display some conditions about the connection on the screen.
 
Note: This server could only respond the GET method request. And the connection will be closed if a request is not having a right format. For example, wrong method, wrong filename format or non-existed filename, etc.
 
ThreadedServer.java
First, compile this java file through cmd:
javac ThreadedServer.java

to ThreadedServer.class. Second, run this class file also through cmd:
java ThreadedServer

Now the server is waiting for request from clients. When clients connecting with it, it will display the count of clients and the other conditions about the connection on the screen.
 
Note: This server could only respond the GET method request. And the connection will be closed if a request is not having a right format. For example, wrong method, wrong filename format or non-existed filename, etc. 



本人编写的代理服务器程序代码如下:
FileName: Client.java
import java.io.*; 
import java.net.*;

/**
* A web client which could connect with a server and do some actions.
*
* @author Zhao Jinjiang
*/

class Client {

  /**
   * Connect with a server and send commands. At last, save the response from
   * the server.
   *
   * @param argv[]
   * The address of server which this client connect with.
   * @throws Exception
   */
  public static void main(String argv[]) throws Exception {

    /* Reader and writer in system */
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(
        System.in));
    PrintWriter stdOut = new PrintWriter(
        new OutputStreamWriter(System.out), true);

    /*
     * If the lenth of argv isn't 1, write the error message and return.
     *
     */
    if (argv.length != 1) {
      stdOut.println("Usage: Client <server>");
      return;
    }

    /* the client socket */
    Socket clientSocket = new Socket(argv[0], 80);

    /* Reader and writer between client and server */
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
        clientSocket.getInputStream()));
    PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(
        clientSocket.getOutputStream()), true);

    stdOut.println(argv[0] + " is listening to your request:");

    /* the command read from user */
    String cmd = "";

    /* the response temporarily read one by one */
    String temp = "";

    /* the web information and html sentencesread from server */
    String recieve = "";
    String display = "";

    /* the condition whether reading sentences html or web information */
    boolean html = false;

    cmd = stdIn.readLine();

    outToServer.println(cmd + "\r\n\r\n");

    /*
     * Read the response from server and identify the content.
     *
     */
    while (true) {
      temp = inFromServer.readLine();
      if (temp == null)
        break;
      if (html == false && temp.length() == 0)
        html = true;
      if (html == false)
        display = display + "\n" + temp;
      else
        recieve = recieve + "\n" + temp;
    }

    stdOut.println("Header:\n" + display);

    /*
     * Output the html sentences into a html file.
     *
     */
    stdOut.print("Enter the name of the file to save:");
    stdOut.flush();

    cmd = stdIn.readLine();

    PrintWriter fileOut = new PrintWriter(new FileWriter(cmd), true);
    fileOut.println(recieve);

    /*
     * Close these reader and writer.
     *
     */
    fileOut.close();
    inFromServer.close();
    outToServer.close();
    stdIn.close();
    stdOut.close();

  }
}


本人编写的代理服务器程序代码如下:
FileName: Server.java
import java.io.*; 
import java.net.*;
import java.util.*;

/**
* A web server which could connect with a client and do some actions.
*
* @author Zhao Jinjiang
*/

public class Server {

  /**
   * Waiting for request and to accept connection from a client.
   *
   * @throws Exception
   */
  public Server() throws Exception {

    /* the server socket */
    ServerSocket serSk = new ServerSocket(8000);

    /*
     * open the socket for client connecting with.
     */
    while (true) {

      /* the client socket */
      Socket cliSk = serSk.accept();

      System.out.println("Accepting Connection...\n");

      /* reader and writer with client and file */
      FileInputStream inFromFile = null;
      BufferedReader inFromClient = null;
      DataOutputStream outToClient = null;

      /* response the request */
      try {
        while (true) {

          inFromClient = new BufferedReader(new InputStreamReader(
              cliSk.getInputStream()));
          outToClient = new DataOutputStream(cliSk.getOutputStream());

          System.out.println("Waiting for command...");
          String cmd = inFromClient.readLine();
          System.out.println("The request for: " + cmd);

          /*
           * Process the command from client and identify the method
           * and address. If command error, write the error response
           * and break.
           *
           */
          StringTokenizer token = new StringTokenizer(cmd);
          if (token.countTokens() < 2) {

            System.out.println("Command style error!");
            outToClient.writeBytes("HTTP/1.1 400 Bad Request\n\r");
            break;

          } else {

            String method = token.nextToken();
            String filename = token.nextToken();

            if (!method.equals("GET")) {
              System.out.println("Method error!");
              outToClient
                  .writeBytes("HTTP/1.1 400 Bad Request\n\r");
              break;
            }

            if (filename.charAt(0) != '/') {
              System.out.println("Filename command error!");
              outToClient
                  .writeBytes("HTTP/1.1 400 Bad Request\n\r");
              break;
            }

            filename = filename.toUpperCase();

            filename = (filename.equals("/") ? "INDEX.HTM"
                : filename.substring(1));

            File file = new File(filename);

            if (!file.exists()) {
              System.out.println("File not existed!");
              outToClient
                  .writeBytes("HTTP/1.1 404 Not Found\n\r");
              break;
            }

            /*
             * Response the right format request. Identify the file
             * tpye and write it to the client.
             *
             */
            System.out.println("Now respond the request...");
            inFromFile = new FileInputStream(filename);

            byte[] by = new byte[(int) file.length()];
            inFromFile.read(by);

            if (filename.endsWith(".HTM")) {
              outToClient.writeBytes("HTTP/1.0 200 OK" + "\n\r");

              outToClient.writeBytes("Content-Type: txt/html"
                  + "\n\r");

              outToClient.writeBytes("Content-Length: "
                  + file.length() + "\n\r\n\r");
            }

            outToClient.write(by);
            outToClient.flush();
            outToClient.writeBytes("\n\r");
            break;
          }
        }

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

        /*
         * Close the reader and writer.
         *
         */
        System.out.println("Closing Connection...\n");

        try {
          if (inFromFile != null)
            inFromFile.close();
          if (inFromClient != null)
            inFromClient.close();
          if (outToClient != null)
            outToClient.close();
          if (cliSk != null)
            cliSk.close();
        } catch (IOException e) {
        }
      }
    }
  }

  /**
   * Open a server socket and request the responses from a client.
   *
   * @param args
   */
  public static void main(String[] args) {

    try {
      Server server = new Server();

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

  }
}


本人编写的代理服务器程序代码如下:
FileName: ThreadServer.java
import java.io.*; 
import java.net.*;
import java.util.*;

/**
* A threaded web server which could connect with clients and do some actions.
*
* @author Zhao Jinjiang
*/

public class ThreadedServer {

  /**
   * Waiting for requests and to accept connections from clients.
   *
   * @throws Exception
   */
  public ThreadedServer() throws Exception {
    
    /* the server socket */
    ServerSocket serSk = new ServerSocket(8000);
    
    /* the counter of clients */
    int counter = 1;

    while (true) {
      Socket cliSk = serSk.accept();
      System.out.println("Accepting Client " + counter + "'s Connection...\n");

      /* a thread for a client */
      ServerThread st = new ServerThread(cliSk, counter++);
      st.start();
    }
  }

  /**
   * Serve for a client socket.
   *
   * @throws Exception
   */
  class ServerThread extends Thread {
    
    /* a client socket */
    private Socket sk;

    /* the counter of clients */
    private int counter;

    ServerThread(Socket sk, int counter) {
      this.sk = sk;
      this.counter = counter;
    }

    public void run() {
      
      /* reader and writer with client and file */
      FileInputStream inFromFile = null;
      BufferedReader inFromClient = null;
      DataOutputStream outToClient = null;
      
      /* response the request */
      try {
        while (true) {
          
          inFromClient = new BufferedReader(new InputStreamReader(sk
              .getInputStream()));
          outToClient = new DataOutputStream(sk.getOutputStream());

          System.out.println("Waiting for Client " + counter
              + "\'s command...");
          String cmd = inFromClient.readLine();
          System.out.println("The Client " + counter + " request for: "
              + cmd);

          /*
           * Process the command from client and identify the method
           * and address. If command error, write the error response
           * and break.
           *
           */
          StringTokenizer token = new StringTokenizer(cmd);
          if (token.countTokens() < 2) {
            
            System.out.println("Command style error!");
            outToClient.writeBytes("HTTP/1.1 400 Bad Request\n\r");
            break;
            
          } else {
            
            String method = token.nextToken();
            String filename = token.nextToken();

            if (!method.equals("GET")) {
              System.out.println("HTTP/1.1 400 Bad Request\n\r");
              break;
            }

            if (filename.charAt(0) != '/') {
              System.out.println("Filename command error!");
              outToClient
                  .writeBytes("HTTP/1.1 400 Bad Request\n\r");
              break;
            }

            filename = filename.toUpperCase();

            filename = (filename.equals("/") ? "INDEX.HTM"
                : filename.substring(1));

            File file = new File(filename);

            if (!file.exists()) {
              System.out.println("File not existed!");
              outToClient
                  .writeBytes("HTTP/1.1 404 Not Found\n\r");
              break;
            }

            /*
             * Response the right format request. Identify the file
             * tpye and write it to the client.
             *
             */
            System.out.println("Now respond the Client " + counter
                + "\'s request...");
            inFromFile = new FileInputStream(filename);

            byte[] by = new byte[(int) file.length()];
            inFromFile.read(by);

            if (filename.endsWith(".HTM")) {
              outToClient.writeBytes("HTTP/1.0 200 OK" + "\n\r");

              outToClient.writeBytes("Content-Type: txt/html"
                  + "\n\r");

              outToClient.writeBytes("Content-Length: "
                  + file.length() + "\n\r\n\r");
            }

            outToClient.write(by);
            outToClient.flush();
            outToClient.writeBytes("\n\r");
            break;
          }
        }

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        
        /*
         * Close the reader, writer and client socket.
         *
         */
        System.out.println("Closing Client " + counter
            + "\'s Connection...\n");

        try {
          if (inFromFile != null)
            inFromFile.close();
          if (inFromClient != null)
            inFromClient.close();
          if (outToClient != null)
            outToClient.close();
          if (sk != null)
            sk.close();
        } catch (IOException e) {
        }
      }
    }
  }

  /**
   * Open a threaded server socket and request the responses from clients.
   *
   * @param args
   */
  public static void main(String[] args) {
    
    try {
      ThreadedServer threadedServer = new ThreadedServer();

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

  }
}
0

评论Comments

日志分类
首页[442]
随笔[88]
分享[81]
音乐[52]
思考[37]
相册[48]
体坛[65]
开发[71]