为什么浏览器不请求数据?java的ServerSocket和socket

huangapple go评论56阅读模式
英文:

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 = &quot;\r\n&quot;;
	public static final String BLANK = &quot; &quot;;
	
	
	public static void main(String[] args) {
		try (ServerSocket server = new ServerSocket(8080)) {
			while (true) {
				Socket client = server.accept();
				new Thread(()-&gt; {
					StringBuilder sb = new StringBuilder();
					try {
						InputStream in = new BufferedInputStream(client.getInputStream());
						OutputStream out = new BufferedOutputStream(client.getOutputStream());
						char ch;
						while ((ch = (char) in.read()) != &#39;\n&#39;) {
							sb.append(ch);
						}

						System.out.println(sb);	
						byte[] body = &quot;I love you yesterday and today!&quot;.getBytes();
					
						// create response header
						StringBuilder headerBuilder = new StringBuilder();
						headerBuilder.append(&quot;HTTP/1.1 200 OK&quot;).append(CRLF)
						.append(&quot;Host:&quot;).append(BLANK).append(client.getInetAddress().getHostName()).append(CRLF)
						.append(&quot;Content-Type:&quot;).append(BLANK).append(&quot;application/json&quot;).append(CRLF)
						.append(&quot;Access-Control-Allow-Origin:&quot;).append(BLANK).append(&quot;*&quot;).append(CRLF)
						.append(&quot;Content-Length:&quot;).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(&quot;StringBuilder object&#39;s length: &quot; + sb.length());
						System.out.println(&quot;StringBuilder object&#39;s content: &quot;);
						System.out.println(sb);
						System.out.println(&quot;========================&quot;);
					} 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&#39;s length: 1207959550
StringBuilder object&#39;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 &quot;Thread-1&quot; java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Arrays.java:3664)
at java.lang.String.&lt;init&gt;(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()) != &#39;\n&#39;) {
        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&#39;t detect -1 that way
if (ch == -1 || ch == &#39;\n&#39;) 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.

huangapple
  • 本文由 发表于 2020年9月10日 20:46:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63829999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定