您的位置:首页 > 理论基础 > 计算机网络

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

2014-04-30 00:46 911 查看
首先是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) {  

          

       
4000
    e.printStackTrace();  

        }  

          

    }  

}  

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

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

代码中借鉴了高人们的许多东西,与大家分享,共同进步,望不吝斧正。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java socket http服务器
相关文章推荐