简体   繁体   中英

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

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. 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. 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.

Try with this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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