我正在用java编写一个简单的客户端服务器程序。客户端向服务器发送文件名。服务器接收它,然后对其进行解析,并在解析文件名后向客户端发送响应,无论文件名是正确还是无效。
在服务器中,当它解析文件名时会抛出 NullPointerException 错误。
这是代码:
Server.java
:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class Server extends Thread {
private static int port;
private ServerSocket serverSocket=null;
private String ReceivedFilename=null;
private String ServerResponse=null;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
//serverSocket.setSoTimeout(20000);
}
public void run() {
while (true) {
try {
System.out.println("Waiting for client to send File name...");
Socket server = serverSocket.accept();
System.out.println("Connected to Client");
DataInputStream in = new DataInputStream(server.getInputStream());
ReceivedFilename = in.readUTF();
System.out.println("Received Filename: "+ReceivedFilename);
if(ReceivedFilename == "")
ServerResponse = "Filename is empty!";
else{
if(ServerResponse.indexOf(".bat") == ServerResponse.length()-4)
{
ServerResponse = "Correct file name provided.";
}
else
{
ServerResponse = "Invalid Filename! Server only accepts .bat files";
}
}
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF(ServerResponse);
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
port = 9000;
try {
Thread t = new Server(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java
:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
private static String serverName;
public static void main(String[] args) {
String sName = "localhost";
int port = 9000;
String Filename = "Scripts.bat";
try {
System.out.println("Connecting to Server");
Socket client = new Socket(sName, port);
System.out.println("Connected to Server");
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
System.out.println("Sending filename to Server");
out.writeUTF(Filename);
System.out.println("Filename sent");
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
}
}
}
以下是服务器上的输出和异常:
请帮忙。