简体   繁体   English

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

[英]Can not receive a response from a remote server

I am trying to write a code that will allow me to connect to a remote server and receive a response from it. 我正在尝试编写一个代码,允许我连接到远程服务器并从中接收响应。 The remote address is : www.euref-ip.net:2101 远程地址是: www.euref-ip.net : 2101

When trying to connect to it from a web page it works fine. 当尝试从网页连接到它时它工作正常。 However when i am trying to connect through my java code i cant get any response back. 但是当我试图通过我的java代码连接时,我无法得到任何回复。 Here is my code so far: 到目前为止,这是我的代码:

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);}
}}

Right now the ln variable is always 0 and I am reading empty response. 现在ln变量总是0,我正在读取空响应。 What am i doing wrong? 我究竟做错了什么? Any suggestions? 有什么建议么? Any help would be appreciated. 任何帮助,将不胜感激。

Your HTTP request is incomplete, you need to add an extra empty line at the end indicating the end of the header section which is also here the end of the request. 您的HTTP请求不完整,您需要在末尾添加一个额外的空行,表示标题部分的结尾,此处也是请求的结尾。

Try with this: 试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM