这是我的代码:
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
。
所以我很卡住。请帮助我弄清楚。
您正在编写的响应肯定是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 OKrn";
byte[] bb = t.getBytes("UTF-8");
out.write(bb);
t = "Content-Length: 124rn";
bb = t.getBytes("UTF-8");
out.write(bb);
t = "Content-Type: text/htmlrnrn";
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
字符串的字节[]。