这是我的代码:
import java.net.*;
import java.io.*;
class Server
{
public static void main(String args[])
{
try
{
ServerSocket svr = new ServerSocket(8900);
System.out.println("waiting for request");
Socket s = svr.accept();
System.out.println("got a request");
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
int x;
byte data[]= new byte[1024];
x = in.read(data);
String response = "<html><head><title>HTML content via java socket</title></head><body><h2>Hi! Every Body.</h2></body></html>";
out.write(response.getBytes());
out.flush();
s.close();
svr.close();
System.out.println("closing all");
}
catch(Exception ex)
{
System.out.println("Err : " + ex);
}
}
}
运行它我希望直接访问Chrome:127.0.0.1:8900
然后看一下html,但实际上Chrome会说以下内容:
This page isn’t working
127.0.0.1 sent an invalid response.
ERR_INVALID_HTTP_RESPONSE
。
我的Server.java
正在按我的意愿运行。 Eclipse中的控制台在连接后很好地说:
waiting for request
got a request
closing all
。
所以我很困惑。请帮我解决一下。
答案 0 :(得分:1)
您正在撰写的回复肯定无法读取Chrome。因为它不包含有关标题中的响应的任何信息
您的代码实际上是发送回复。您可以使用curl
进行检查。
以下代码将帮助您获取chrome中的响应。
ServerSocket svr = new ServerSocket(8900);
System.out.println("waiting for request");
Socket s = svr.accept();
System.out.println("got a request");
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
int x;
byte data[] = new byte[1024];
x = in.read(data);
String t = "HTTP/1.1 200 OK\r\n";
byte[] bb = t.getBytes("UTF-8");
out.write(bb);
t = "Content-Length: 124\r\n";
bb = t.getBytes("UTF-8");
out.write(bb);
t = "Content-Type: text/html\r\n\r\n";
bb = t.getBytes("UTF-8");
out.write(bb);
String response = "<html><head><title>HTML content via java socket</title></head><body><h2>Hi! Every Body.</h2></body></html>";
out.write(response.getBytes("UTF-8"));
t = "Connection: Closed";
bb = t.getBytes("UTF-8");
out.write(bb);
out.flush();
s.close();
svr.close();
System.out.println("closing all");
如果您更改response
至关重要,则必须计算Content-Length:
,因为它将是response
字节[]和字节[]的长度Connection: Closed
字符串。