1

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.

1 Answers1

0

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";
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • OK, thank you I will try. However the first line you added does not appear in the request when i am trying to connect from the same web browser to a server running from a java code, that way i can print out the request. –  Aug 08 '16 at 16:23
  • It worked. It seems that the critical thing is the extra empty line at the end. Thank you. –  Aug 08 '16 at 16:27