I am writing a raw socket server (for learning purpose), which on any request, should parse the Content-Length header and should then extract bytes equal to Content-Length from the socket input stream and echo it back to the client.
I found only one class 'DataInputStream' in Java IO system that provides with the capabilities of reading both, characters and bytes. However, the method readLine() of 'DataInputStream' is deprecated which I am using in my code. How can I get rid of the deprecated readLine() method in following code? Is there any class in Java IO system that allows reading of both, characters and bytes. Code follows:
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;
}
}