java实现一个简单的HTTP服务器,带打开网页和计算功能

首先是WebServer类,定义了端口(8080)和serverSocket


package org.cust.oo;


import java.io.IOException;  
import java.net.ServerSocket;  
import java.net.Socket;  
  
public class WebServer {  
  
    /** 
     * @param args 
     */  
  
    public void serverStart(int port) {  
        try {  
            ServerSocket serverSocket = new ServerSocket(port);  
            while (true) {  
                /* accept()方法:Listens for a connection to be made to this socket and accepts it.  
                 * The method blocks until a connection is made.  
                 */  
                Socket socket = serverSocket.accept();  
                new ConnectionThread(socket).start();  
            }  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
  
    }  
  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
  
        int port = 8080;//定义服务器端口号,该端口号不可被其他进程占用  
        if (args.length == 1) {  
            port = Integer.parseInt(args[0]);  
        }  
        new WebServer().serverStart(port);//调用服务器启动方法  
  
    }  
  
}  



然后是ConnectionThread类,里面具体实现了如何打开指定的html文件,和计算出表达式相应的结果

package org.cust.oo;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;


import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
  
public class ConnectionThread extends Thread {  
  
    private Socket socket;  
    private InputStream in;  
    private PrintStream out;  
    public final static String WEB_ROOT = "E:\\open\\17\\java_me\\IntenetOfCompture\\bin\\org\\cust\\oo\\";//该目录下需要存在html文档  
    public ConnectionThread(Socket socket) {  
        this.socket = socket;  
          
        try {  
            in = socket.getInputStream();  
            out = new PrintStream(socket.getOutputStream());  
        } catch (IOException e) {  
          
            e.printStackTrace();  
        }  
          
    }  
  
    public void run() {  
        String fileName = this.parse(in);  
        System.out.println(fileName);
        this.sendFile(fileName);  
    }  
  
    public String parse(InputStream in) {  
  
        BufferedReader br = new BufferedReader(new InputStreamReader(in));  
        String fileName = null;
        String expression = null;
        try {  
            String httpMessage = br.readLine();  
            String[]content = httpMessage.split(" ");//协议状态号,名称,版本号  
              
            //如果客戶端輸入协议错误则返回错误页面  
            if(content.length != 3) {  
                this.sendErrorMessage(400, "Client query error!");  
                return null;  
            }  
            //否则输出协议信息  
            System.out.println("code:  "+content[0]+",address:"+content[1]+  
                    ",httpversion:  "+content[2]); 
 
            System.out.println(content[1]);
            String Parameter[] = content[1].split("[?]");
            fileName = Parameter[0];
            System.out.println("fileName:"+fileName);
            expression = Parameter[1];
            System.out.println("expression:"+expression);
            /**
             * 
             * 实现对表达式的分析计算
             */
         ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        try {
    String result = engine.eval(expression).toString();
    System.out.println("表达式计算结果为:"+result);
    } catch (ScriptException e) {
    e.printStackTrace();
    }


            
        } catch (IOException e) {  
              
            e.printStackTrace();  
        }  
        return fileName;  
  
    }  
  
    //错误页面输出方法  
    public void sendErrorMessage(int ErrorCode, String ErrorContent) {  
  
        out.println("HTTP/1.0 "+ErrorCode+" "+ErrorContent);  
        out.println("content-type: text/html");  
        out.println();  
        out.println("<html>");  
          
        out.println("<title>Error Message");  
        out.println("</title>");  
        out.println("<body>");  
        out.println("<h1>ErrorCode:"+ErrorCode+",Message:"+ErrorContent+"</h1>");         
          
        out.println("</body>");  
        out.println("</html>");  
          
        out.flush();  
        out.close();  
        try {  
            in.close();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }  
  
    public void sendFile(String fileName) {  
        File file = new File(ConnectionThread.WEB_ROOT+fileName);  
        if(!file.exists()) {  
            this.sendErrorMessage(404, "file not found");  
            return ;  
        }  
        try {  
            InputStream in = new FileInputStream(file);  
            byte content[] = new byte[(int)file.length()];  
            try {  
                in.read(content);  
                out.println("HTTP/1.0 200 queryfile");  
                out.println("content-length:"+content.length);  
                out.println();  
                out.write(content);  
                out.flush();  
                in.close();  
            } catch (IOException e) {  
                  
                e.printStackTrace();  
            }  
        } catch (FileNotFoundException e) {  
          
            e.printStackTrace();  
        }  
          
    }  
}  


启动程序后,在浏览器中输入http://local:8080/index.html。即可看到对应的页面,前提是你要有index.html在对应的目录下

在浏览器中输入http://local:8080/index.html?3+4 , 可在控制台上看到计算结果。

代码中借鉴了高人们的许多东西,与大家分享,共同进步,望不吝斧正。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值