首页 > 代码库 > SimpleHttpServer 阻塞模式

SimpleHttpServer 阻塞模式

SimpleHttpServer.java

import java.io.FileInputStream;import java.io.IOException;import java.net.InetSocketAddress;import java.net.Socket;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.channels.FileChannel;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.nio.charset.Charset;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class SimpleHttpServer {    private int port = 8088;    private ServerSocketChannel serverSocketChannel = null;    private ExecutorService executorService;    private static final int POOL_MULTIPLE = 4;        public SimpleHttpServer() throws IOException {        executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_MULTIPLE);        serverSocketChannel = ServerSocketChannel.open();        serverSocketChannel.socket().setReuseAddress(true);        serverSocketChannel.socket().bind(new InetSocketAddress(port));        System.out.println("Server Starting...");    }            public void service() {        while(true) {            SocketChannel socketChannel = null;            try {                socketChannel = serverSocketChannel.accept();                executorService.execute(new Handler(socketChannel));            }            catch (IOException e) {                e.printStackTrace();            }        }    }            public static void main(String[] args) throws IOException {        new SimpleHttpServer().service();    }            class Handler implements Runnable {                private SocketChannel socketChannel;                public Handler(SocketChannel socketChannel) {            this.socketChannel = socketChannel;        }                public void run() {            handle(socketChannel);        }                public void handle(SocketChannel socketChannel) {                        FileInputStream in = null;                        try {                Socket socket = socketChannel.socket();                System.out.println("Connecting from: " + socket.getInetAddress() + ":" + socket.getPort());                                ByteBuffer buffer = ByteBuffer.allocate(1024);                socketChannel.read(buffer);                buffer.flip();                String request = decode(buffer);                System.out.print(request);                                StringBuffer sb = new StringBuffer("HTTP/1.1 200 OK\r\n");                sb.append("Content-Type:text/html\r\n\r\n");                socketChannel.write(encode(sb.toString()));                                String firstLineOfRequest = request.substring(0, request.indexOf("\r\n"));                if(firstLineOfRequest.indexOf("login.htm") != -1)                    in = new FileInputStream("login.htm");                else                    in = new FileInputStream("hello.htm");                                FileChannel fileChannel = in.getChannel();                fileChannel.transferTo(0, fileChannel.size(), socketChannel);            }            catch (Exception e) {//                e.printStackTrace();            }            finally {                try {                    if(socketChannel != null)                         socketChannel.close();                    if(in != null)                         in.close();                }                catch (IOException e) {                    e.printStackTrace();                }            }        }                        private Charset charset = Charset.defaultCharset();                public String decode(ByteBuffer buffer) {                        CharBuffer charbuff = charset.decode(buffer);            return charbuff.toString();        }                public ByteBuffer encode(String str) {                        return charset.encode(str);        }    }}

 

login.htm

<html lang="zh-cn"><head>    <title>login.htm</title>    <meta charset="utf-8"> </head><body>    <form name="loginForm" method="post" action="hello.htm">    /* <form name="loginForm" method="get" action="hello.htm"> */        <table>            <tr><td><div align="right">用户名: </div></td>                <td><input type="text" name="username"></td>            </tr>            <tr><td><div align="right">口令: </div></td>                <td><input type="password" name="password"></td>            </tr>            <tr><td></td>                <td><input type="submit" name="submit" value="submit"></td>            </tr>        </table>    </form></body></html>

 

hello.htm

<html lang="zh-cn"><head>    <title>hello.htm</title>    <meta charset="utf-8"> </head><body>    <p>It works!</p></body></html>

 

// GET request (default)GET /login.htm HTTP/1.1Accept: */*Accept-Language: zh-CNUser-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; qdesk 2.5.1277.202; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)Accept-Encoding: gzip, deflateHost: 127.0.0.1:8088Connection: Keep-Alive

 

// POST requestPOST /hello.htm HTTP/1.1Accept: image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*Referer: http://127.0.0.1:8088/login.htmAccept-Language: zh-CNUser-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; qdesk 2.5.1277.202; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)Content-Type: application/x-www-form-urlencodedAccept-Encoding: gzip, deflateHost: 127.0.0.1:8088Content-Length: 49Connection: Keep-AliveCache-Control: no-cacheusername=username&password=password&submit=submit

 

// Get request with variablesGET /hello.htm?username=username&password=password&submit=submit HTTP/1.1Accept: image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*Referer: http://127.0.0.1:8088/login.htmAccept-Language: zh-CNUser-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; qdesk 2.5.1277.202; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)Accept-Encoding: gzip, deflateHost: 127.0.0.1:8088Connection: Keep-Alive

 

SimpleHttpServer 阻塞模式