【发布时间】:2021-07-06 08:44:54
【问题描述】:
我正在为大学做一些工作,其中要求我创建一个 TCP 套接字,该套接字以 OPTIONS 作为标头发出 HTTP 请求,并在变量中返回整个页面。
我制作的代码如下:
public String SendReq(String url, int port) throws Exception {
String resposta = null;
// Instantiate a new socket
Socket s = new Socket(url, port);
// Instantiates a new PrintWriter passing in the sockets output stream
PrintWriter wtr = new PrintWriter(s.getOutputStream());
// Prints the request string to the output stream
wtr.println("OPTIONS / HTTP/1.1");
wtr.println("Host: " + url);
wtr.println("");
wtr.flush();
// Creates a BufferedReader that contains the server response
BufferedReader bufRead = new BufferedReader(new InputStreamReader(s.getInputStream()));
String outStr;
while ((outStr = bufRead.readLine()) != null) {
resposta = resposta + outStr;
if (!outStr.trim().isEmpty()) {
resposta += "\r\n";
}
}
LSimLogger.log(Level.INFO, "response http : " + resposta);
s.close();
bufRead.close();
wtr.close();
return resposta ;
}
而且确实有效。
如您所见,我使用 example.org 作为 url 和 80 作为端口运行此代码。在日志中,我看到:
10-04-2021 21:35:49:514 tcp_client [INFO] : inici client http
10-04-2021 21:35:49:517 tcp_client [INFO] : inici HTTPclient.get
10-04-2021 21:35:49:517 tcp_client [INFO] : HTTP server_address: example.org
10-04-2021 21:35:49:517 tcp_client [INFO] : HTTP server_port: 80
10-04-2021 21:35:49:517 tcp_client [INFO] : example.org
10-04-2021 21:38:00:636 tcp_client [INFO] : response http : nullHTTP/1.1 200 OK
Allow: OPTIONS, GET, HEAD, POST
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Sat, 10 Apr 2021 19:35:49 GMT
Expires: Sat, 17 Apr 2021 19:35:49 GMT
Server: EOS (vny/0452)
Content-Length: 0
如您所见,得到响应需要3分钟多,但响应日期与请求相同。
我可以做些什么来加快响应速度?
【问题讨论】:
-
3 分钟听起来有点像保命
-
不完全是 3 分钟,大约是 3 分钟
标签: java performance sockets tcp