非常慢的Apache httpserver响应(httpcore 4.3.2 libs)

时间:2014-06-16 12:07:49

标签: java apache netbeans

我使用httpcore库4.3.2制作自定义http服务器与某些客户端(Android设备)进行通信。

客户端设法与服务器进行通信(发布xml),但服务器的响应非常慢。

我的代码基于apache样本的ElementalHttpServer。我能为httpcore库找到更好的样本吗? 此外,我无法找到如何设置参数或微调http服务器,因为不推荐使用HttParams库。

如果我使用com.sun.net.httpserver.HttpServer httpserver我的客户端连接没有问题。最好留在太阳队或使用阿帕奇?

提前致谢。

这是我使用的代码:

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.SSLServerSocketFactory;
import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpConnectionFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultBHttpServerConnection;
import org.apache.http.impl.DefaultBHttpServerConnectionFactory;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.protocol.UriHttpRequestHandlerMapper;
import org.apache.http.util.EntityUtils;

public class Thread_Main_httpcore2 implements Runnable {

    public Thread_Main_httpcore2() {

    }//Thread_Main()

    @Override
    public void run() {
        int port = 20010;

        // Set up the HTTP protocol processor
        HttpProcessor httpproc = HttpProcessorBuilder.create()
                .add(new ResponseDate())
                .add(new ResponseServer("Test/1.1"))
                .add(new ResponseContent())
                .add(new ResponseConnControl()).build();

        // Set up request handlers
        UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();

        //// Set up the HTTP service
        HttpService httpService = new HttpService(httpproc, reqistry);

        reqistry.register("*", new Thread_Main_httpcore2.HttpReqHandler());

        SSLServerSocketFactory sf = null;

        try {
            Thread t = new RequestListenerThread(port, httpService, sf);
            t.setDaemon(false);
            t.start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    static class HttpReqHandler implements HttpRequestHandler {

        public HttpReqHandler() {
            super();
        }

        public void handle(
                final HttpRequest request,
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {

                String xml_stream="";


            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                byte[] entityContent;
                if (entity == null) {
                    entityContent = new byte[0];
                } else {
                    entityContent = EntityUtils.toByteArray(entity);
                }

                //byte[] entityContent = EntityUtils.toByteArray(entity);
                System.out.println("Incoming entity content (bytes): " + entityContent.length);

                xml_stream = new String(entityContent);
            }

            StringBuilder resp_xml = new StringBuilder();
                resp_xml.append("Returns an xml to the client");

            StringEntity entity;
            try {
                response.setStatusCode(HttpStatus.SC_OK);
                entity = new StringEntity(resp_xml.toString(), ContentType.create("text/html", "UTF-8"));
                response.setEntity(entity);

            } catch (Exception ex_send_resp) {
                System.out.println("HttpFileHandler.ex_send_resp "+ ex_send_resp.toString());
            }

        }

    }

    static class RequestListenerThread extends Thread {

        private final HttpConnectionFactory<DefaultBHttpServerConnection> connFactory;
        private final ServerSocket serversocket;
        private final HttpService httpService;

        public RequestListenerThread(
                final int port,
                final HttpService httpService,
                final SSLServerSocketFactory sf) throws IOException {
            this.connFactory = DefaultBHttpServerConnectionFactory.INSTANCE;
            this.serversocket = sf != null ? sf.createServerSocket(port) : new ServerSocket(port);
            this.httpService = httpService;
        }

        @Override
        public void run() {
            System.out.println("Listening on port " + this.serversocket.getLocalPort());
            while (!Thread.interrupted()) {
                try {
                    // Set up HTTP connection
                    Socket socket = this.serversocket.accept();
                    System.out.println("Incoming connection from " + socket.getInetAddress());
                    HttpServerConnection conn = this.connFactory.createConnection(socket);

                    // Start worker thread
                    Thread t = new WorkerThread(this.httpService, conn);
                    t.setDaemon(true);
                    t.start();
                } catch (InterruptedIOException ex) {
                    break;
                } catch (IOException e) {
                    System.err.println("I/O error initialising connection thread: "
                            + e.getMessage());
                    break;
                }
            }
        }
    }

    static class WorkerThread extends Thread {

        private final HttpService httpservice;
        private final HttpServerConnection conn;

        public WorkerThread(
                final HttpService httpservice,
                final HttpServerConnection conn) {
            super();
            this.httpservice = httpservice;
            this.conn = conn;
        }

        @Override
        public void run() {
            System.out.println("New connection thread");
            HttpContext context = new BasicHttpContext(null);
            try {
                while (!Thread.interrupted() && this.conn.isOpen()) {
                    this.httpservice.handleRequest(this.conn, context);
                }
            } catch (ConnectionClosedException ex) {
                System.err.println("Client closed connection");
            } catch (IOException ex) {
                System.err.println("I/O error: " + ex.getMessage());
            } catch (HttpException ex) {
                System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
            } finally {
                try {
                    this.conn.shutdown();
                } catch (IOException ignore) {
                }
            }
        }

    }

}

0 个答案:

没有答案
相关问题