方枪枪的java世界

不要因为风雨飘落就停止了你的脚步,真正的得失就在你的心中。 做喜欢做的事,不轻言放弃!

01 一个简单的HttpServer_SimpleHttpServer_Constant

 

package com.tianhe.frm.http;

public interface Constant
{

   public static String CONTENT_LENGTH = "Content-Length:";   
}


package com.tianhe.frm.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import com.tianhe.frm.context.GlobalConfig;
import com.tianhe.frm.exception.OurRuntimeException;
import com.tianhe.frm.utils.LogUtil;
import com.tianhe.frm.utils.ObjectUtil;
import com.tianhe.frm.utils.StringUtil;

public class SimpleHttpServer implements Runnable
{
    private boolean debug = false;
   
    private String charset = "gbk";
   
    private ServerSocket serverSocket;// 服务器Socket
   
    private static Processor processor = null;
   
    public SimpleHttpServer(int port, String charset, boolean debug)
    {
        this.debug = debug;
       
        if (StringUtil.isNotEmpty(charset))
        {
            this.charset = charset;
        }
       
        this.serverSocket = createServerSocket(port);
        if (this.serverSocket != null)
        {
            new Thread(this).start();
            System.out.println("SimpleHttpServer is running, port=" + port + ",charset=" + charset + ",debug=" + debug);
        }
    }
   
    private ServerSocket createServerSocket(int port)
    {
        ServerSocket ss = null;
       
        try
        {
            ss = new ServerSocket(port);
        }
        catch (IOException e)
        {
            throw new OurRuntimeException("createServerSocket failed", e);
        }
        return ss;
    }
   
    public void run()
    {
        while (true)
        {
            try
            {
                Socket socket = serverSocket.accept();
                new Thread(new ServerHandler(socket)).start();
            }
            catch (IOException e)
            {
                getLog().error("SimpleHttpServer run error", e);
            }
           
        }
    }
   
    class ServerHandler implements Runnable
    {
        private Socket socket;
       
        ServerHandler(Socket socket)
        {
            this.socket = socket;
        }
       
        public void run()
        {
            try
            {
                boolean firstFlag = false;
                String resource = "";
                String method = "";
                int len = 0;
               
                StringBuffer sb = new StringBuffer();
                String line;
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while ((line = in.readLine()) != null)
                {
                    sb.append(line).append("\n");
                   
                    if (!firstFlag)
                    {
                        resource = line.substring(line.indexOf('/') + 1, line.lastIndexOf('/') - 5);
                        resource = URLDecoder.decode(resource, charset);// 反编码 URL
                       
                        method = new StringTokenizer(line).nextElement().toString();// 获取请求方法, GET 或者 POST
                        firstFlag = true;
                    }
                   
                    if (line.startsWith(Constant.CONTENT_LENGTH))
                    {
                        len = Integer.valueOf(line.substring(Constant.CONTENT_LENGTH.length()));
                    }
                   
                    if (line.equals(""))
                        break;
                }
               
                // 显示 POST 表单提交的内容, 这个内容位于请求的主体部分
                char[] reqData = null;
                if ("POST".equalsIgnoreCase(method) && len > 0)
                {
                    reqData = new char[len];
                    in.read(reqData);
                    sb.append(new String(reqData)).append("\n");
                }
               
                String requestString = sb.toString();
                System.out.println("-------------------------begin----------------------------");
                System.out.println(requestString);
                System.out.println("-------------------------end------------------------------");
               
                byte[] resData = processRequest(resource, reqData, charset);
                writeResponse(resource, resData, socket);
            }
            catch (IOException e)
            {
                throw new OurRuntimeException("ServerHandler run error", e);
            }
            finally
            {
                closeSocket(socket);
            }
        }
    }
   
    public byte[] processRequest(String resource, char[] data, String charset)
    {
        if (processor == null)
        {
            String clazzName = GlobalConfig.getString("ProcessorImpl.CLASS_NAME", "com.tianhe.frm.http.ProcessorImpl");
            processor = (Processor)ObjectUtil.createObject(clazzName);
        }
       
        byte[] resData = processor.process(resource, data, charset);
        return resData;
    }
   
    private void writeResponse(String resource, byte[] resData, Socket socket)
    {
        try
        {
            PrintStream out = new PrintStream(socket.getOutputStream(), true);
            out.println("HTTP/1.0 200 OK");
            out.println("Content-Type:text/html;charset=" + charset);
            if (resData != null)
            {
                out.println("Content-Length:" + resData.length);
                out.println();
                out.write(resData);
            }
            else
            {
                out.println("Content-Length: 0");
                out.println();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
   
    void closeSocket(Socket socket)
    {
        try
        {
            if (socket != null)
            {
                socket.close();
            }
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
   
    private Logger getLog()
    {
        return LogUtil.getLog(getClass());
    }
   
    private static void usage()
    {
        System.out.println("Usage: java SimpleHttpServer -port 8080 -charset gbk -debug");
    }
   
    public static void main(String[] args)
    {
        try
        {
            String charset = "GBK";
            int port = 8080;
            boolean debug = false;
           
            if (args != null && args.length > 0)
            {
                for (int i = 0; i < args.length; i++)
                {
                   
                    if (args[i].startsWith("-port"))
                    {
                        port = Integer.valueOf(args[i + 1]);
                        i++;
                    }
                   
                    if (args[i].startsWith("-charset"))
                    {
                        charset = args[i + 1];
                        i++;
                    }
                   
                    if (args[i].startsWith("-debug"))
                    {
                        debug = true;
                        // i++;
                    }
                   
                    if (args[i].equalsIgnoreCase("-help"))
                    {
                        usage();
                        System.exit(0);
                    }
                }
            }
           
            new SimpleHttpServer(port, charset, debug);
        }
        catch (OurRuntimeException ex)
        {
            ex.printStackTrace();
        }
       
    }
}

posted on 2012-07-09 22:11 做强大的自己 阅读(219) 评论(0)  编辑  收藏 所属分类: Socket


只有注册用户登录后才能发表评论。


网站导航: