Recently, I wanted to verify a computer network problem. So, I wrote a program, and at first it worked. But occasionally, it makes an error - outof memory error. After testing, I found that my code is wrong. I read a byte directly and then convert it into a character. I don't know why. Sometimes there is no data in the connection. The program only reads a - 1, and then converts - 1 into a character, But the whole program can't stop. So, I want to know, what is the reason for this mistake? I don't know whether it's the browser or the program. I hope you can help me solve this problem.
Here is my code:
package org.dragon;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class CheckServer {
public static final String CRLF = "\r\n";
public static final String BLANK = " ";
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(8080)) {
while (true) {
Socket client = server.accept();
new Thread(()-> {
StringBuilder sb = new StringBuilder();
try {
InputStream in = new BufferedInputStream(client.getInputStream());
OutputStream out = new BufferedOutputStream(client.getOutputStream());
char ch;
while ((ch = (char) in.read()) != '\n') {
sb.append(ch);
}
System.out.println(sb);
byte[] body = "I love you yesterday and today!".getBytes();
// create response header
StringBuilder headerBuilder = new StringBuilder();
headerBuilder.append("HTTP/1.1 200 OK").append(CRLF)
.append("Host:").append(BLANK).append(client.getInetAddress().getHostName()).append(CRLF)
.append("Content-Type:").append(BLANK).append("application/json").append(CRLF)
.append("Access-Control-Allow-Origin:").append(BLANK).append("*").append(CRLF)
.append("Content-Length:").append(BLANK).append(body.length).append(CRLF)
.append(CRLF);
System.out.println(headerBuilder);
// response header
byte[] header = headerBuilder.toString().getBytes(StandardCharsets.UTF_8);
// return response message
out.write(header);
out.write(body);
// flush the stream
out.flush();
} catch (Throwable e) {
e.printStackTrace();
System.out.println("StringBuilder object's length: " + sb.length());
System.out.println("StringBuilder object's content: ");
System.out.println(sb);
System.out.println("========================");
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I use browser to visit the http://localhost:8080, If you visit many times or after a while, there will be errors. And, here is the Error infomation:
GET / HTTP/1.1
HTTP/1.1 200 OK
Host: 0:0:0:0:0:0:0:1
Content-Type: application/json
Access-Control-Allow-Origin: *
Content-Length: 31
java.lang.OutOfMemoryError: Java heap space
StringBuilder object's length: 1207959550
StringBuilder object's content:
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:124)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:649)
at java.lang.StringBuilder.append(StringBuilder.java:202)
at org.dragon.CheckServer.lambda$0(CheckServer.java:28)
at org.dragon.CheckServer$$Lambda$1/135721597.run(Unknown Source)
at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-1" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Arrays.java:3664)
at java.lang.String.<init>(String.java:207)
at java.lang.StringBuilder.toString(StringBuilder.java:407)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at org.dragon.CheckServer.lambda$0(CheckServer.java:56)
at org.dragon.CheckServer$$Lambda$1/135721597.run(Unknown Source)
at java.lang.Thread.run(Thread.java:748)
When I attempt to print the sb, it occur an Exception, but I think this is not a problem. And I really want to know why the code will read no data?
char ch;
while ((ch = (char) in.read()) != '\n') {
sb.append(ch);
}
Is the request sent by the browser empty?
Notice: I know that I can't directly convert the read byte into a character. I have to judge whether it is - 1. If it is - 1, I can ignore it. But I don't understand why there is such a request?
As written, your code reads data off the wire and adds it to a stringbuilder, which is a thing in memory.
Your code will continue to do this until the character \n
is encountered. Note that the read()
method will return -1, and will continue to do so forever, if the stream has ended. That means you add an endless sequence of -1
characters to the stringbuilder, forever. Except of course, 'forever' isn't quite forever: Once you run out of memory to store that infinite sequence of -1, you get this.
The solution is trivial: Stop looping when that .read() call returns -1, or \n. Save the result in a local variable and you can then simply check. Something like:
while (true) {
int ch = in.read(); // do NOT cast to char, you can't detect -1 that way
if (ch == -1 || ch == '\n') break;
sb.append((char) ch); // cast here.
}
Don't ignore -1 – end the loop on -1. There is no more data coming. ever. If you're waiting for a newline char it will never occur.
Hey, it's networking. You don't get any guarantees.