我是套接字编程的新手,我试图让我的客户端程序从我桌面上的文档中检索网址,将此网址发送到我的服务器程序,并获取我的服务器 - 程序将此url-website的html代码作为字符串发回: 当我尝试将字符串发回给我的客户时,我一直收到NPE,有人能指出我做错了什么吗?
服务器程序:
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();
}
}
}
答案 0 :(得分:1)
问题在于您的服务器:
您使用__declspec(noinline)
bool IsEqual(Vector2D & a, Vector2D & b) {
// etc..
}
初始化StringBuilder
:
null
然后尝试在null引用上调用方法:
StringBuilder htmlCode = null;
尝试
htmlCode = htmlCode.append(line);
代替。这应解决StringBuilder htmlCode = new StringBuilder();
。
答案 1 :(得分:0)
在您为其提供非空值之前,您正在使用htmlCode
。
StringBuilder htmlCode = null;
...
htmlCode = htmlCode.append(line);
您可以预先初始化它:
StringBuilder htmlCode = new StringBuilder();
...
htmlCode = htmlCode.append(line);