我寫了一個服務器類,我的客戶端是我的瀏覽器。當我在瀏覽器中輸入localhost:8082
時,打開了硬編碼網站www.mmix.cs.hm.edu
。到現在爲止還挺好。 一個網站通常有多個頁面。無論我點擊其他鏈接,我的服務器只能檢索主頁www.mmix.cs.hm.edu/index.html
。我希望能夠導航到這些其他頁面。任何人都可以看看我的代碼,並告訴我如何繼續?客戶端 - 服務器應用程序Java
public static void main(String args[]) {
String fromClient = "www.mmix.cs.hm.edu";
try(ServerSocket welcomeSocket = new ServerSocket(8082)){
System.out.println("Server started, waiting for clients...");
while(true){
StringBuilder htmlCode = new StringBuilder();
try(Socket connectionSocket = welcomeSocket.accept();
DataOutputStream toClient = new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader fromBrowser = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()))){
try(InputStream url = new URL("http://"+fromClient+"/index.html").openStream();
BufferedReader getUrl = new BufferedReader(new InputStreamReader(url))){
for(String line = getUrl.readLine(); line != null; line = getUrl.readLine()){
htmlCode.append(line);
}
String str = htmlCode.toString();
toClient.writeBytes(str);
//toClient.write("\r\n");
}
}
}
}
catch(IOException io){
io.printStackTrace();
}
}
考慮使用''而不是'URL'來直接將客戶端連接中的數據傳遞到服務器。 '新插座(「www.mmix.cs.hm.edu」,80)'。這將是更容易,更乾淨。 –