同时从java套接字输入流执行字符和字节输入

时间:2015-11-02 16:05:16

标签: java serversocket java-io datainputstream

我正在编写一个原始套接字服务器(用于学习目的),在任何请求中,它应该解析Content-Length头,然后从套接字输入流中提取等于Content-Length的字节并将其回送给客户端

我发现只有一个类' DataInputStream'在Java IO系统中,它提供了读取字符和字节的功能。但是,' DataInputStream'的方法readLine()已弃用,我在我的代码中使用。如何在以下代码中删除已弃用的readLine()方法? Java IO系统中是否有允许读取字符和字节的类。代码如下:

class Server {
    public Server() {
    }

    public void run() throws IOException {
        ServerSocket serverSocket = new ServerSocket(7000);

        while (true) {
            Socket socket = serverSocket.accept();
            DataInputStream requestStream = new DataInputStream(
                    new BufferedInputStream(socket.getInputStream()));

            byte[] responseContent = null;
            int contentLength = getContentLength(requestStream);
            if (contentLength == 0)
                responseContent = new byte[0];
            else {
                int totalBytesRead = 0, bytesRead = 0;
                final int bufferSize = 5120;
                final byte[] buffer = new byte[bufferSize];
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                while (totalBytesRead != contentLength) {
                    bytesRead = requestStream.read(buffer, 0, bufferSize);
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                }
                responseContent = outputStream.toByteArray();
            }

            OutputStream outputStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(outputStream);
            writer.println(String.format("HTTP/1.1 %s", 200));
            writer.println(String.format("Content-Length: %d", contentLength));
            writer.println("");
            writer.flush();
            outputStream.write(responseContent);
            outputStream.flush();
            socket.close();
        }
    }

    private int getContentLength(DataInputStream requestStream)
            throws IOException {
        int contentLength = 0;
        String headerLine;
        // TODO - Get rid of deprecated readLine() method
        while ((headerLine = requestStream.readLine()) != null
                && headerLine.length() != 0) {
            final String[] headerTokens = headerLine.split(":");
            if (headerTokens[0].equalsIgnoreCase("Content-Length")) {
                contentLength = Integer.valueOf(headerTokens[1].trim());
            }
        }
        return contentLength;
    }
}

0 个答案:

没有答案