简体   繁体   English

Java构建基本WebServer如何将标头发送到浏览器

[英]Java Building a Basic WebServer how do i send headers to browser

I'm still learning java and trying to build a basic WebServer using Sockets for now i have the server working and sending output data back to the browser but i'm unsure how to send the headers i thought they were just "\\r\\n\\r\\n" from the content body 我还在学习java并尝试使用套接字构建一个基本的WebServer现在我让服务器工作并将输出数据发送回浏览器但是我不确定如何发送标题我认为它们只是“\\ r \\ n \\ r \\ n“来自内容正文

This is how i'm writing to the browser currently 这就是我当前正在写入浏览器的方式

Socket socket = socketServer.accept();
System.out.println("Web Request From: "+socket.getInetAddress().toString());

BufferedReader in = new BufferedReader(
     new InputStreamReader(socket.getInputStream())
);
PrintWriter out = new PrintWriter(socket.getOutputStream());
Stirng output = "<!DOCTYPE html><html><body><h1>403 Forbidden</h1></body></html>"
out.write(output, 0, output.lenght());
out.flush();
out.close();

Put the headers in the output string, separated from each other by \\r\\n and from the main body by \\r\\n\\r\\n . 放头在输出串,由彼此分离\\r\\n和从主体由\\r\\n\\r\\n Or, with the PrintWriter just print them one by one, an empty line, and then the body. 或者,PrintWriter只需逐个打印,空行,然后是正文。

You should take a look at NanoHttpd . 你应该看一下NanoHttpd Its a one file Web server and its a lot of fun to play with. 它是一个单文件Web服务器,玩起来很有趣。 They are sending headers back, so you should be able to look at their code fairly easily and see what they are doing. 他们正在发送回头,所以你应该能够相当容易地查看他们的代码并看看他们在做什么。

your forced to send the HTTP information first 你被迫首先发送HTTP信息

out.println("HTTP/1.0 200"); 

is required before any other codes send or the main body 在任何其他代码发送或主体之前需要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM