我是新來的套接字編程,我試圖讓我的客戶端程序從我的桌面上的文檔檢索URL,發送此URL到我的服務器程序,並讓我的服務器程序以字符串的形式發回這個url-website的html代碼: 當我嘗試將字符串發回給我的客戶端時,我總是收到NPE,任何人都可以指向我做錯了什麼?客戶端 - 服務器套接字編程Java
服務器程序:
public class Server {
public static void main(String args[]) {
String fromClient;
StringBuilder htmlCode = null;
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())){
fromClient = inFromClient.readLine();
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()){
//THIS IS WHERE ECLIPSE SAYS NPE IS HAPPENING
htmlCode = htmlCode.append(line);
}
str = htmlCode.toString();
toClient.writeBytes(str);
}
}
}
}
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"));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))){
url = inFromUser.readLine();
outToServer.writeBytes(url + "\n");
returned = inFromServer.readLine();
System.out.println("FROM SERVER: " + returned);
}
catch(IOException io){
io.printStackTrace();
}
}
}
謝謝。這解決了它。 –