简体   繁体   English

Java HTTP Server错误:服务器中的文件意外结束

[英]Error with Java HTTP Server: Unexpected end of file from server

java.net.SocketException: Unexpected end of file from server java.net.SocketException:服务器中的文件意外结束

The client sends a query to the server by using an URL. 客户端使用URL向服务器发送查询。 I have a HTTPServer that parses info from the URL. 我有一个HTTPServer,它从URL解析信息。 Using that info, the server does some work and then returns the response to the client. 服务器使用该信息进行一些工作,然后将响应返回给客户端。

Let's say the URL is: 假设网址为:

http://localhost:9090/find?term=healthy&term=cooking&count=3

This works fine. 这很好。 But when count is greater or equal to 4, I get java.net.SocketException. 但是当count大于或等于4时,我得到java.net.SocketException。 To debug the error, I print out the URL. 为了调试该错误,我打印出了URL。 System.out.println(input); System.out.println(输入); When count>=4, the URL gets printed two times in the console. 当count> = 4时,URL将在控制台中打印两次。 Please help. 请帮忙。

private final HttpServer server;
public Server(int port){
  server = HttpServer.create(new InetSocketAddress(port), MAX_BACKLOG);
  server.createContext("/isbn", new ISBNHandler());
  server.createContext("/find", new TitleHandler());
}

static class TitleHandler implements HttpHandler {
  public void handle(HttpExchange t) throws IOException {
    int count=5;
    String input=t.getRequestURI().toASCIIString();//get the URL
    System.out.println(input);
    //using info from URL to do some work
    String response = builder.toString();//StringBuilder
    // System.out.println(response);
    t.sendResponseHeaders(200, response.getBytes().length);
    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());
    os.close();
  }
}

Exception 例外

java.net.SocketException: Unexpected end of file from server at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source) at sun.net.www.http.HttpClient.parseHTTP(Unknown Source) at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source) at sun.net.www.http.HttpClient.parseHTTP(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) at TestHarness.assertJSONResponse(TestHarness.java:101) at TestHarness.testServer(TestHarness.java:38) at TestHarness.main(TestHarness.java:25) java.net.SocketException:位于sun.net.www.http.HttpClient.parseHTTPHeader(服务器未知)处的文件来自sun.net.www.http.HttpClient.parseHTTP(服务器源未知)位于sun.net.www .http.HttpClient.parseHTTPHeader(未知来源)在sun.net.www.http.HttpClient.parseHTTP(未知来源)在sun.net.www.protocol.http.HttpURLConnection.getInputStream(未知来源)在java.net.HttpURLConnection TestHarness.main的.getResponseCode(未知源).assertJSONResponse(TestHarness.java:101).TestServer(TestHarness.java:38)在TestHarness.main(TestHarness.java:25)

TestHarness 测试线束

 import java.io.*;
    import java.net.HttpURLConnection;
     import java.net.URL;
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

/**
 * Sample main method with initial acceptance tests to help you along
 */
public class TestHarness {
    private static Pattern MAP_PATTERN = Pattern.compile("(['\"])(.*?)\\1:\\s*(['\"])(.*?)\\3");
    private static Pattern LIST_PATTERN = Pattern.compile("\\{(.*?)\\}");

    public static void main(String[] args) throws IOException {
        /*
        if (args.length < 1) {
            System.out.println("The test harness requires a single parameter: the location of the CSV file to parse");
        }
        */
        BookServer server = new BookServer(9090, new File("books.csv"));
        server.start();
        testServer();
        server.stop();
    }

    /**
     * Run initial acceptance tests
     */
    @SuppressWarnings("unchecked")
    private static void testServer() {
        assertJSONResponse("Book Test", "http://localhost:9090/isbn/9780470052327",
                createMap("isbn", "9780470052327", "title", "Techniques of Healthy Cooking", "author", "Mary Dierdre Donovan", "publisher", "Wiley", "publishedYear", "2007"));
        assertJSONResponse("Book Test", "http://localhost:9090/isbn/9780451169525",
                        createMap("isbn", "9780451169525", "title", "Misery", "author", "Stephen King", "publisher", "Signet", "publishedYear", "1987"));
        assertJSONResponse("Query Test", "http://localhost:9090/find?term=healthy&term=cooking&count=4",
                        Arrays.asList(createMap("isbn", "9780470052327", "title", "Techniques of Healthy Cooking", "author", "Mary Dierdre Donovan", "publisher", "Wiley", "publishedYear", "2007")));

    }

    /**
     * Helper method to convert the vararg parameters into a Map. Assumes alternating key, value, key, value... and calls
     * toString on all args
     *
     * @param args the parameters to put in the map, alternating key ancd value
     * @return Map of String representations of the parameters
     */
    private static Map<String, String> createMap(Object ... args) {
        Map<String, String> map = new HashMap<String, String>();
        for (int i=0; i < args.length; i+=2) {
            map.put(args[i].toString(), args[i+1].toString());
        }
        return map;
    }

    /**
     * Parses a JSON list of maps
     * NOTE: assumes all keys and values in the nested maps are quoted
     *
     * @param content the JSON representation
     * @return a list of parsed Map content
     */
    private static List<Map<String, String>> parseJSONList(CharSequence content) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        Matcher m = LIST_PATTERN.matcher(content);
        while(m.find()) {
            list.add(parseJSONMap(m.group(1)));
        }
        return list;
    }

    /**
     * Parse JSON encoded content into a Java Map.
     * NOTE: Assumes that all elements in the map are quoted
     *
     * @param content the JSON representation to be parsed
     * @return A map of parsed content
     */
    private static Map<String, String> parseJSONMap(CharSequence content) {
        Map<String, String> map = new HashMap<String, String>();
        Matcher m = MAP_PATTERN.matcher(content);
        while (m.find()) {
            map.put(m.group(2), m.group(4));
        }
        return map;
    }

    /**
     * Retrieve content from a test URL and assert that its content is the expected. Results will be printed to System.out for convenience
     *
     * @param testName Name of the test, to be used simply for labelling
     * @param urlString The URL to test
     * @param expected The content expected at that URL
     */
    private static void assertJSONResponse(String testName, String urlString, Object expected) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection con = ((HttpURLConnection)url.openConnection());
            if (!assertTest(testName + " - response code", con.getResponseCode(), 200)) return;

            StringBuilder b = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line;
            while((line = r.readLine()) != null) b.append(line);
            String result = b.toString();
            assertTest(testName + " - content retrieved", !result.isEmpty(), true);

            Object parsed = result.trim().startsWith("[") ? parseJSONList(result) : parseJSONMap(result);
            assertTest(testName + " - parsed content match", parsed, expected);
        } catch (Exception e) {
            System.out.println(testName + ": <<<FAILED with Exception>>>");
            e.printStackTrace(System.out);
        }
    }

    /**
     * Log the results of a test assertion
     *
     * @param testName Name of the test, to be used simply for labelling
     * @param result The result of the operation under test
     * @param expected The expected content that the result will be compared against
     * @return whether the test was successful
     */
    private static boolean assertTest(String testName, Object result, Object expected) {
        boolean passed = result.equals(expected);
        System.out.println(testName + (passed ? ": <<<PASSED>>>" : String.format(": <<<FAILED>>> expected '%s' but was '%s'", expected, result)));
        return passed;


      }
    }

I fixed the error. 我修复了错误。 The server calls a private sorting function, but I made a bug in the sorting function. 服务器调用了私有排序功能,但是我在排序功能中犯了一个错误。 The server crashed. 服务器崩溃了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 tableau服务器错误:服务器中的文件意外结束 - tableau server error: Unexpected end of file from server java.net.SocketException:来自服务器的文件意外结束 - java.net.SocketException: Unexpected end of file from server 引起:java.net.SocketException:来自服务器的文件意外结束 - Caused by: java.net.SocketException: Unexpected end of file from server 异常:java.net.SocketException:来自服务器的文件意外结束 - Exception: java.net.SocketException: Unexpected end of file from server 如何处理“来自服务器的文件意外结束”? - how to deal with “Unexpected end of file from server”? org.testng.TestNGException:java.net.SocketException:使用 Selenium 和 TestNG 和 Maven 的服务器错误文件意外结束 - org.testng.TestNGException: java.net.SocketException: Unexpected end of file from server error using Selenium with TestNG and Maven Java简单代码:java.net.SocketException:来自服务器的文件意外结束 - Java simple code: java.net.SocketException: Unexpected end of file from server URLConnection无法发送完整的URL(java.net.SocketException:服务器上的文件意外结束) - URLConnection does not send full URL (java.net.SocketException: Unexpected end of file from server) HttpUrlConnection getOutputStream()抛出java.net.SocketException:服务器上的文件意外结束 - HttpUrlConnection getOutputStream() throwing java.net.SocketException: Unexpected end of file from server Solr SimplePostTool:读取响应时出现IOException:java.net.SocketException:服务器中的文件意外结束 - Solr SimplePostTool: IOException while reading response: java.net.SocketException: Unexpected end of file from server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM