这是我第一次制作网络服务器。我想创建一个代理服务器。目前,我已将服务器设置为" 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());
}
}
}
答案 0 :(得分:0)
HTTP请求中的反斜杠应为正斜杠。