无法从远程服务器接收响应

Can not receive a response from a remote server

我正在尝试编写允许我连接到远程服务器并接收来自它的响应的代码。 远程地址是: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";