英文:
Why does the browser request no data?java's ServerSocket and socket
问题
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();
}
}
}
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)
char ch;
while ((ch = (char) in.read()) != '\n') {
sb.append(ch);
}
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?
英文:
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?
答案1
得分: 0
无限的字符串构建器
如所述,你的代码从网络中读取数据并将其添加到字符串构建器中,这是内存中的一个对象。
只要遇到字符\n
,你的代码将继续执行此操作。请注意,如果流已结束,read()
方法将返回-1,并且会一直返回-1,这意味着你会不断地将无限数量的-1
字符添加到字符串构建器中,一直这样进行下去。当然,“一直”并不是真的一直:一旦你用完了存储这个无限序列的内存,你就会遇到这个问题。
解决方法很简单:当.read()
调用返回-1或\n
时停止循环。将结果保存在一个局部变量中,然后你可以简单地检查。类似这样:
while (true) {
int ch = in.read(); // 不要转换为char,这样无法检测到-1
if (ch == -1 || ch == '\n') break;
sb.append((char) ch); // 在这里进行强制类型转换。
}
不要忽略-1 - 当-1出现时结束循环。没有更多的数据了。永远不会。如果你在等待换行符,它将永远不会出现。
那么为什么会发生这种情况呢?
嘿,这是网络。你得不到任何保证。
英文:
infinite stringbuilder
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.
Okay so why is this happening?
Hey, it's networking. You don't get any guarantees.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论