gpt4 book ai didi

java - 无法接收来自远程服务器的响应

转载 作者:太空宇宙 更新时间:2023-11-04 12:21:16 25 4
gpt4 key购买 nike

我正在尝试编写一段代码,允许我连接到远程服务器并接收来自它的响应。远程地址是:www.euref-ip.net:2101

当尝试从网页连接到它时,它工作正常。然而,当我尝试通过我的 java 代码连接时,我无法得到任何响应。这是到目前为止我的代码:

public class Client implements Runnable{
private String nServer = "";
private int nPort = 0;

public Client(String server, int port){
this.nServer = server;
this.nPort = port;
}

@Override
public void run() {
try {
SocketAddress sockaddr = new InetSocketAddress(nServer, nPort);
Socket s = new Socket();
s.connect(sockaddr, 10 * 1000);
if (s.isConnected()) {
s.setSoTimeout(20 * 1000);
DataOutputStream out = new DataOutputStream (s.getOutputStream());
DataInputStream in = new DataInputStream (s.getInputStream());
while (true) {
// send a message to the server
String requestmsg = "GET / HTTP/1.0\r\n";
requestmsg += "User-Agent: Client v1\r\n";
requestmsg += "Accept: */* \r\n";
requestmsg += "Connection: keep alive\r\n";
out.write(requestmsg.getBytes());
out.flush();

// receive a response
int ln = in.available();
byte [] bytes = new byte [ln];
in.read(bytes);
System.out.println(new String(bytes) + "\n");
Thread.sleep(2000);
}
}
}
catch (UnknownHostException ex) {System.out.println(ex);}
catch (IOException ex) {System.out.println(ex);}
catch (InterruptedException ex) {System.out.println(ex);}
}}

现在 ln 变量始终为 0,并且我正在读取空响应。我究竟做错了什么?有什么建议么?任何帮助,将不胜感激。

最佳答案

您的 HTTP 请求不完整,您需要在末尾添加一个额外的空行,指示 header 部分的结尾,这也是请求的结尾。

试试这个:

String requestmsg = "GET / HTTP/1.0\r\n";
...
requestmsg += "Connection: keep alive\r\n";
requestmsg += "\r\n";

关于java - 无法接收来自远程服务器的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38833840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com