我是socket编程的新手。我有一个客户端从我桌面上的txt文件中检索URL并通过套接字将其传递给服务器。服务器将网页的html代码检索为sting,替换字符串中的一些标记并将字符串(html-code)发送回客户端。当我将它输出到我的控制台时,我能够看到字符串,但是当我尝试将其传递给本地txt / html文件时,我得到一个空白文件/页面。有人能指出我做错了吗?
服务器:
public class Server {
public static void main(String args[]) {
String fromClient = "";
StringBuilder htmlCode = new StringBuilder();
StringBuilder fClient = new StringBuilder();
String str = null;
try(ServerSocket welcomeSocket = new ServerSocket(8082)){
System.out.println("Server started, waiting for clients...");
while(true){
try(Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream toClient = new DataOutputStream(connectionSocket.getOutputStream())){
for(String line = inFromClient.readLine(); line != null && line.length()>0; line = inFromClient.readLine()){
fClient.append(line);
}
if(fClient.toString().contains("www.mmix.cs.hm.edu")){
fromClient = "www.mmix.cs.hm.edu";
}
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);
}
str = htmlCode.toString();
String imgReplaced = replaceImgs(str);
String replaced = replaceYou(imgReplaced);
toClient.writeBytes(replaced);
}
}
}
}
catch(IOException io){
io.printStackTrace();
}
}
客户端:
public class Client {
public static void main(String[] args) {
String url;
String returned;
try(Socket clientSocket = new Socket("localhost", 8082);
BufferedReader inFromUser = new BufferedReader(new FileReader("C:\\Users\\Anthony\\Desktop\\client.txt"));
BufferedWriter toServer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter toBrowser = new BufferedWriter(new FileWriter("C:\\Users\\Anthony\\Desktop\\MMIX.txt"))){
url = inFromUser.readLine();
toServer.write("GET /index.html HTTP/1.0\r\n");
toServer.write("Host: "+url+"\r\n");
toServer.write("\r\n");
toServer.flush();
returned = inFromServer.readLine();
//Output to the console works
System.out.println("FROM SERVER: " + returned);
//Output to the stream toBrowser which writes to a txt file, not working
for(returned = inFromServer.readLine(); returned != null && returned.length() > 0; returned = inFromServer.readLine()){
toBrowser.write(returned);
System.out.println(returned);
}
}
catch(IOException io){
io.printStackTrace();
}
}
}