[英]Can not receive a response from a remote server
我正在嘗試編寫一個代碼,允許我連接到遠程服務器並從中接收響應。 遠程地址是: 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.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);}
}}
現在ln
變量總是0,我正在讀取空響應。 我究竟做錯了什么? 有什么建議么? 任何幫助,將不勝感激。
您的HTTP請求不完整,您需要在末尾添加一個額外的空行,表示標題部分的結尾,此處也是請求的結尾。
試試這個:
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.