littlefermat

          基于命令行的簡單的HTTP客戶端和服務器

          1.實現HTTP 1.0 GET命令的客戶端

            1/**
            2 *這是一個簡單的HTTP客戶端程序
            3 * @author wangliang
            4 */

            5package http;
            6
            7import java.io.BufferedInputStream;
            8import java.io.BufferedReader;
            9import java.net.Socket;
           10import java.io.FileOutputStream;
           11import java.io.IOException;
           12import java.io.InputStreamReader;
           13import java.io.PrintWriter;
           14import java.io.File;
           15import java.util.StringTokenizer;
           16
           17/**
           18 *這是一個簡單的HTTP客戶端程序,你可以實現HTTP1.0的GET命令
           19 * @author wangliang
           20 */

           21
           22
           23public class Client {
           24
           25    public static void main(String args[]) throws Exception {
           26        if (args.length == 2{
           27            Client client = new Client(args[0], Integer.parseInt(args[1]));
           28            client.run();
           29        }
           else if (args.length == 0{
           30            Client client2 = new Client("www.whu.edu.cn"80);
           31            client2.run();
           32        }
           else {
           33            System.out.println("ERROR.You should input as below");
           34            System.out.println("java Client host port or java Client");
           35        }

           36    }

           37    String host;
           38    int port;
           39
           40    public Client(String host, int port) {
           41        this.host = host;
           42        this.port = port;
           43    }

           44
           45    /**與服務器建立連接,發送GET請求命令*/
           46   public void run() {
           47        Socket socket;
           48        BufferedInputStream in;
           49        PrintWriter out;
           50        try {
           51            socket = new Socket(host, port);
           52            System.out.println(socket.getRemoteSocketAddress());
           53            System.out.println("連接成功");
           54            in = new BufferedInputStream(socket.getInputStream());
           55            out = new PrintWriter(socket.getOutputStream(), true);
           56            try {
           57                BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
           58                String userInput;
           59                while ((userInput = stdIn.readLine()) != null{
           60                    if (userInput.equalsIgnoreCase("quit")) {
           61                        System.out.println("關閉瀏覽器");
           62                        System.exit(0);
           63                    }

           64                    out.println(userInput);
           65                    out.println();
           66                    System.out.println(userInput);
           67                    int mark = 0;
           68                    int word = -1;
           69                    byte data[] = new byte[0];
           70                    byte data2[] = new byte[1000];
           71                    while ((word = in.read(data2, 01000)) != -1{
           72                        byte temp[] = data;
           73                        data = new byte[data.length + word];
           74                        System.arraycopy(temp, 0, data, 0, temp.length);
           75                        System.arraycopy(data2, 0, data, temp.length, word);
           76                    }

           77                    for (int i = 0; i < data.length; i++{
           78                        if (data[i] == 13 && data[i + 1== 10 && data[i + 2== 13 && data[i + 3== 10{
           79                            mark = i + 4;
           80                            break;
           81                        }

           82                    }

           83                    byte head[] = new byte[mark];
           84                    System.arraycopy(data, 0, head, 0, mark);
           85                    System.out.println("頭文件:");
           86                    System.out.println(new String(head));
           87                    byte file[] = new byte[data.length - mark];
           88                    System.arraycopy(data, mark, file, 0, data.length - mark);
           89                    save(userInput, file);
           90                    //重新建立連接
           91                    System.out.println("重新建立連接");
           92                    socket = new Socket(host, port);
           93                    System.out.println(socket.getRemoteSocketAddress());
           94                    System.out.println("連接成功");
           95                    in = new BufferedInputStream(socket.getInputStream());
           96                    out = new PrintWriter(socket.getOutputStream(), true);
           97                }

           98
           99            }
           catch (IOException e1) {
          100                e1.printStackTrace();
          101            }

          102        }
           catch (IOException e2) {
          103            System.out.println("連接失敗");
          104            e2.printStackTrace();
          105            System.exit(0);
          106        }

          107    }

          108
          109   /**保存get獲取的文件*/
          110    void save(String userInput, byte bf[]) {
          111        StringTokenizer t = new StringTokenizer(userInput, " ");
          112        if (t.countTokens() < 2{
          113            return;
          114        }

          115        t.nextToken();
          116        String t2 = t.nextToken();
          117        int last = t2.lastIndexOf("/");
          118        //獲取文件名
          119        String filename = t2.substring(last + 1, t2.length());
          120        if (filename.equals("")) {
          121            filename = "index.html";
          122        }

          123        String dir = t2.substring(0, last);
          124        //獲取文件的目錄
          125
          126        File dirs = new File(host + dir);
          127        dirs.mkdirs();
          128        File file = new File(dirs, filename);
          129        try {
          130            FileOutputStream out = new FileOutputStream(file);
          131            out.write(bf);
          132            System.out.println("文件" + filename + "成功保存到文件夾" + host + dir);
          133        }
           catch (Exception e) {
          134            // TODO Auto-generated catch block
          135            System.out.println("文件保存失敗");
          136        }

          137    }

          138}

          139
          直接打印頭文件,保存GET的文件;沒有分析響應頭的代碼
          2.簡單的每請求線程模型服務器
          ThreadedServer監聽一個端口,對每個Socket請求生成一個Handler線程進行處理,服務器文件放在一個www文件夾中
           1/*
           2 * To change this template, choose Tools | Templates
           3 * and open the template in the editor.
           4 */

           5package http;
           6
           7import java.net.ServerSocket;
           8
           9/*
          10 * To change this template, choose Tools | Templates
          11 * and open the template in the editor.
          12 */

          13import java.net.Socket;
          14
          15/**
          16 *這是一個多線程簡單的HTTP服務器程序,它可以接受HTTP1.0的GET命令
          17 * @author wangliang
          18 */

          19public class ThreadedServer {
          20
          21    String serverName;
          22    String Version;
          23    int serverport;
          24
          25    public static void main(String args[]) {
          26        ThreadedServer server = new ThreadedServer("HTTPSServer""1.0"801);
          27        server.run();
          28    }

          29
          30    public ThreadedServer(String name, String version, int port) {
          31        serverName = name;
          32        Version = version;
          33        serverport = port;
          34    }

          35
          36    /**為客戶端的每個請求啟動一個線程處理用戶的請求*/
          37    public void run() {
          38        int count=1;
          39        System.out.println(serverName + " version:" + Version);
          40        try {
          41            ServerSocket server = new ServerSocket(serverport);
          42            do {
          43                Socket client = server.accept();
          44                (new Handler(client)).start();
          45                System.out.println("Now " + (count+++ " requests received!");
          46            }
           while (true);
          47        }
           catch (Exception e) {
          48            e.printStackTrace();
          49            System.exit(1);
          50        }

          51    }

          52}

          53
          /*
           * To change this template, choose Tools | Templates
           * and open the template in the editor.
           
          */

          package http;


          import java.io.BufferedReader;
          import java.io.DataOutputStream;
          import java.io.File;
          import java.io.FileInputStream;
          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.net.Socket;

          /*
           * To change this template, choose Tools | Templates
           * and open the template in the editor.
           
          */

          import java.util.Date;
          import java.util.StringTokenizer;

          /**
           *ThreadedServer的幫助類,處理用戶的每一個請求
           * 
          @author wangliang
           
          */

          public class Handler extends Thread{
              
          private Socket connectionSocket;
              
              
          public Handler(Socket socket){
                  
          this.connectionSocket=socket;
              }

              
              
          public void run(){
                  
          try{
                 String fileName
          =""
                 String requestMessageLine; 
                 BufferedReader inFromClient
          = 
                   
          new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); 
                 DataOutputStream outToClient
          = 
                   
          new DataOutputStream(connectionSocket.getOutputStream()); 
                 requestMessageLine
          =inFromClient.readLine(); 
                 StringTokenizer tokenizedLine
          = 
                   
          new StringTokenizer(requestMessageLine); 
                 
          if(tokenizedLine.nextToken().equals("GET"))
                   fileName
          =tokenizedLine.nextToken();
                   
          if(fileName.equals("/")==true) fileName="index.html";
                   
          else if(fileName.startsWith("/")==true){
                       fileName
          =fileName.substring(1);
                       
          if (fileName.endsWith("/")) {
                                  fileName 
          = fileName + "index.html";
                              }

                   }
           
                   File file
          =new File("www/"+fileName); 
                   
          if (file.exists()&&file.isFile()){
                       
          int numOfBytes=(int)file.length(); 
                   FileInputStream inFile
          =new FileInputStream(file); 
                   
          byte[] fileInBytes=new byte[numOfBytes]; 
                   inFile.read(fileInBytes); 
                   outToClient.writeBytes(
          "HTTP/1.0 200 Document Follows\r\n"); 
                   outToClient.writeBytes(
          "Date:"+new Date()+"\r\n");
                   outToClient.writeBytes(
          "Server:My client\r\n");
                   
          if(fileName.endsWith(".jpg")) 
                     outToClient.writeBytes(
          "Content-Type:image/jpeg\r\n"); 
                   
          if(fileName.endsWith(".html")) 
                     outToClient.writeBytes(
          "Content-Type:text/html\r\n"); 
                   outToClient.writeBytes(
          "Content-Length:"+ 
                     numOfBytes
          +"\r\n"); 
                   outToClient.writeBytes(
          "\r\n"); 
                   outToClient.write(fileInBytes,
          0,numOfBytes); 
                   connectionSocket.close();
                   }

                   
          else {
                       String notfound
          ="<html><head><title>Not Found</title></head><body><h1>Error 404-file not found</h1></body></html>";
                       outToClient.writeBytes(
          "HTTP/1.0 404 no found\r\n");
                       outToClient.writeBytes(
          "Date:"+new Date()+"\r\n");
                       outToClient.writeBytes(
          "Server:My client\r\n");
                       outToClient.writeBytes(
          "Content_Type:text/html\r\n");
                       outToClient.writeBytes(
          "Content_Length:"+notfound.length()+2+"\r\n");
                       outToClient.writeBytes(notfound);
                       outToClient.close();
                   }
             
                 }
           
                 
          else System.out.println("Bad Request Message"); 
                 }

                  
          catch(IOException e){
                      System.out.println(
          "IOException occured.");
                      e.printStackTrace();
                  }

              }

          }



          posted on 2008-04-13 00:31 littlefermat 閱讀(1746) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 南平市| 准格尔旗| 新建县| 涟源市| 徐汇区| 剑川县| 铜陵市| 宝鸡市| 晋中市| 安阳市| 平邑县| 荥经县| 永顺县| 枣庄市| 克山县| 德惠市| 景谷| 宣威市| 武功县| 田林县| 阿拉善右旗| 泉州市| 阿城市| 扶风县| 光山县| 博野县| 丰顺县| 淮安市| 揭西县| 富锦市| 汝州市| 新疆| 福海县| 登封市| 牟定县| 澳门| 礼泉县| 濮阳市| 都匀市| 昌都县| 岐山县|