Dany Lavrov Dany Lavrov - 2 months ago 9x
Java Question

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;

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";

// receive a response
int ln = in.available();
byte [] bytes = new byte [ln];
System.out.println(new String(bytes) + "\n");
catch (UnknownHostException ex) {System.out.println(ex);}
catch (IOException ex) {System.out.println(ex);}
catch (InterruptedException ex) {System.out.println(ex);}

Right now the
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";