无法使我的Http Server多线程?我正在使用Java HttpServer API [英] Unable to make my Http Server multithreaded? I'm using Java HttpServer API

查看:123
本文介绍了无法使我的Http Server多线程?我正在使用Java HttpServer API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段将HttpServer设置为多线程,但仍可作为单线程使用.请您帮帮我吗?我正在使用Java HttpServer API:

I have a following code snippet to make my HttpServer a multithreaded one,but its still working as single threaded.Can you please help me out? I'm using Java HttpServer API :

// Bind to port 8083
httpServer = HttpServer.create(new InetSocketAddress(HTTP_PORT), 0);

// Adding '/send' context
httpServer.createContext("/send", new SendHandler());

ExecutorService executor = Executors.newCachedThreadPool();
httpServer.setExecutor(executor);

// Start the server
httpServer.start();

完整的Java类:

public class GCMMockServer {

    static HttpServer httpServer;
    static final int HTTP_PORT = 8083;

    public static void main(String[] args) {
        GCMMockServer.start();
    }

    public static void start() {
        try {
            // Bind to port 8083
            httpServer = HttpServer.create(new InetSocketAddress(HTTP_PORT), 0);

            // Adding '/send' context
            httpServer.createContext("/send", new SendHandler());

            ExecutorService executor = Executors.newCachedThreadPool();
            httpServer.setExecutor(executor);

            // Start the server
            httpServer.start();

            System.out.println("GCM Mock Server started at (localhost,8083)");
        } catch (IOException ex) {
            Logger.getLogger(GCMMockServer.class.getName()).log(Level.SEVERE,
                    null, ex);
        }
    }

    public static void stop() {
        httpServer.stop(5);
    }

    // Handler for '/send' context
    static class SendHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange he) throws IOException {
            System.out.println("Serving the request");

            // Serve for POST requests only
            if (he.getRequestMethod().equalsIgnoreCase("POST")) {

                try {
                    // REQUEST Headers
                    Headers requestHeaders = he.getRequestHeaders();
                    Set<Map.Entry<String, List<String>>> entries = requestHeaders
                            .entrySet();

                    System.out.println("Inside POST method");

                    int contentLength = Integer.parseInt(requestHeaders
                            .getFirst("Content-length"));
                    List<String> contentTypes = null;

                    for (Iterator<Entry<String, List<String>>> iterator = entries
                            .iterator(); iterator.hasNext();) {
                        Entry<String, List<String>> entry = iterator.next();
                        String key = entry.getKey();
                        System.out.println("Key : " + key + ", values : ");
                        if (key.equalsIgnoreCase("Content-type")) {
                            contentTypes = entry.getValue();
                        }
                        for (Iterator<String> iterator2 = entry.getValue()
                                .iterator(); iterator2.hasNext();) {
                            String value = iterator2.next();
                            System.out.println("-----------" + value);
                        }
                    }

                    System.out.println("Content length : " + contentLength);

                    // REQUEST Body
                    InputStream is = he.getRequestBody();

                    if (contentTypes.contains("application/json")) {

                        InputStreamReader isr = new InputStreamReader(is,
                                "utf-8");
                        BufferedReader br = new BufferedReader(isr);

                        // From now on, the right way of moving from bytes to
                        // utf-8 characters:

                        int b;
                        StringBuilder buf = new StringBuilder(512);
                        while ((b = br.read()) != -1) {
                            buf.append((char) b);
                        }

                        JSONObject req = new JSONObject(buf.toString());
                        System.out.println("Request body : " + req);
                        String to = (String) req.get("to");
                        String message = (String) ((JSONObject) req.get("data"))
                                .get("message");
                        System.out.println("Request message : " + message
                                + ", to : " + to);
                    }

                    // RESPONSE Headers
                    Headers responseHeaders = he.getResponseHeaders();
                    System.out.println("Response Headers : "
                            + responseHeaders.toString());

                    String response = "Message received";
                    // Send RESPONSE Headers
                    he.sendResponseHeaders(HttpURLConnection.HTTP_OK,
                            response.length());

                    // RESPONSE Body
                    OutputStream os = he.getResponseBody();

                    os.write(response.getBytes());

                    is.close();
                    os.flush();
                    os.close();
                    he.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (he.getRequestMethod().equalsIgnoreCase("GET")) {
                System.out.println("Nothing to serve in GET request type");

                // RESPONSE Headers
                Headers responseHeaders = he.getResponseHeaders();
                String response = "Hi This is Sandeep";
                System.out.println("Response Headers : "
                        + responseHeaders.toString());

                // Send RESPONSE Headers
                he.sendResponseHeaders(HttpURLConnection.HTTP_OK,
                        response.length());

                // RESPONSE Body
                OutputStream os = he.getResponseBody();
                OutputStreamWriter osw = new OutputStreamWriter(os);

                osw.write(response);

                // is.close();
                osw.close();
                os.close();
                he.close();
            }

        }
    }
}

推荐答案

考虑更改handle方法的开始:

 @Override
 public void handle(HttpExchange he) throws IOException {
    System.out.println("Serving the request from Thread "
          + Thread.currentThread().getName() + " / " 
          + Thread.currentThread().getId());
    try {
      Thread.sleep(5000);
    } catch(InterruptedException ie) {
       ie.printStackTrace();
       return;
    }
    System.out.println("Continue request in Thread "
          + Thread.currentThread().getName() + " / " 
          + Thread.currentThread().getId());

现在启动服务器,打开浏览器,加载URL,在5秒内刷新twise并查看控制台日志.

Now start the server, open up a browser, load your url, refresh twise within 5s and watch your console log.

我觉得您会看到多个线程很好.

I have a feeling you'll be seeing multiple threads just fine.

关于您的测试:

您使用的 Test 单线程(一个for循环).因此,在任何一次 中,您的servlet只会有一个活动调用.由于for循环的下一个迭代仅在最后一个循环完成后才开始,因此执行程序线程池中的上一个线程被回收.根据您的测试,根本没有不需要进行多线程处理.

The Test you use is single threaded (a for-loop). So there will be only one active invocation of your servlet at any one time. As the next iteration of your for loop will only start once the last one is finished, the previous thread in the executor thread pool was recycled. There simply was no need for mutlithreading based on your test.

这篇关于无法使我的Http Server多线程?我正在使用Java HttpServer API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆