发信人: flyfly (阿飞), 信区: Npsos
标  题: webserver
发信站: 哈工大紫丁香 (Tue May 27 17:38:45 2003) , 转信


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

class WebServer extends Thread{

public Socket connectionSocket;
public String requestMessageLine;
public String fileName;

public WebServer(Socket a){
     connectionSocket=a;
     }

public  void run(){
         try{
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.startsWith("/")==true)
             fileName=fileName.substring(1);

        File file=new File(fileName);

        
        int numOfBytes=(int)file.length();


        FileInputStream inFile=new FileInputStream(
            fileName);


       byte[] fileInBytes=new byte[numOfBytes];
       inFile.read(fileInBytes);
       outToClient.writeBytes(
        "HTTP/1.0 200 Document Follows\r\n");
       if(fileName.endsWith(".jpg"))
          outToClient.writeBytes(
          "Conent-TYpe:image/jpeg\r\n");
       if(fileName.endsWith(".gif"))
          outToClient.writeBytes(
          "Conent-TYpe:image/jpeg\r\n");
          outToClient.writeBytes(
          "Content-Length:"+numOfBytes+"\r\n");
          outToClient.writeBytes("\r\n");
           outToClient.write(fileInBytes,0,numOfBytes);
      }
        else System.out.println("Bad Request Message");



  }
             
   catch(Exception ex){
        
         System.out.print("ERROR:"+ex.toString());
         }
         try {
   connectionSocket.close();}
   catch (IOException ioe){
   System.out.println(ioe);}
   }
   public static void main(String argv[])throws Exception
    {
      ServerSocket listenSocket=new ServerSocket(6789);
      while(true){
            Socket oldconnectionSocket=listenSocket.accept();
     Thread a=new WebServer(oldconnectionSocket);
     a.start();

     }
     }
}


--

※ 来源:.哈工大紫丁香 http://bbs.hit.edu.cn [FROM: 202.118.225.237]
[百宝箱] [返回首页] [上级目录] [根目录] [返回顶部] [刷新] [返回]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:2.274毫秒