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



我正试图编写一个代码,允许我连接到远程服务器并从它接收响应。远端地址为: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.0rn";
                requestmsg += "User-Agent: Client v1rn";
                requestmsg += "Accept: */* rn";
                requestmsg += "Connection: keep alivern";
                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请求不完整,您需要在末尾添加额外的空行,指示标题部分的结束,这也是请求的结束。

试试这个:

String requestmsg = "GET / HTTP/1.0rn";
...
requestmsg += "Connection: keep alivern";
requestmsg += "rn";

相关内容

  • 没有找到相关文章

最新更新