1
這是我第一次製作網絡服務器。我想創建一個代理服務器。目前,我將服務器設置爲「www.google.com」,而不是對HTTP請求進行任何解析。代理服務器沒有得到服務器的響應
我在命令行上運行ProxyServer,然後在另一個命令行窗口中使用「telnet server_name 5000」調用服務器,然後調用「GET/HTTP/1.1」。
一切工作,直到處理服務器響應的while循環。沒有打印出來。爲什麼?
所有幫助表示讚賞。
import java.net.*;
import java.io.*;
public class ProxyServer {
public static void main(String[] args) throws IOException {
int proxyServerPortNumber = 5000;
String hostName = "www.google.com";
int portNumber = 80;
try {
// SERVER
// Open socket connection and bind it to proxyServerPortNumber
ServerSocket serverSocket =
new ServerSocket(proxyServerPortNumber);
// Listen and accept request
Socket clientSocket = serverSocket.accept();
System.out.println("client request accepted");
// send to client socket
PrintWriter sendToClient =
new PrintWriter(clientSocket.getOutputStream(), true);
// get from client socket
BufferedReader getFromClient = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
// CLIENT
// open socket connection
Socket echoSocket = new Socket(hostName, portNumber);
// send to server
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
// get from server
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
String clientRequest;
// clientRequest = "GET/HTTP/1.1\r\n\r\n";
while ((clientRequest = getFromClient.readLine()) != null) {
System.out.println("in while loop");
System.out.println(clientRequest);
out.println(clientRequest); // send to server
System.out.println("sent to server");
//Get response from server
String response;
while ((response = in.readLine()) != null) // no response why?
{
sendToClient.println("echo: " + response);
System.out.println("echo:" + response);
}
} // end while loop
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
哦,我意識到我的描述與我的代碼不一致。讓我再試一次。 – user234159
好的我修復了請求,服務器仍然沒有返回 – user234159
也許你應該看看你的客戶端代碼是否可以在不使用代理服務器的情況下連接。 – fdsa