你好我正在使用向量和線程寫一個聊天服務器前的代碼, 但我得到這個錯誤,我不知道爲什麼?服務器中的java.lang.NullPointerException
發生錯誤:ClientList.add(new Personnel(nekname,client));
這是我的代碼:
public class chatServer {
private static ServerSocket serverSocket;
private static final int PORT = 5002;
public static Vector<Personnel> ClientList;
public static void main(String[ ] args) throws IOException
{
try {
serverSocket = new ServerSocket(PORT);
ClientList = new Vector<Personnel>();
}
catch (IOException ioEx) {
System.out.println("\nUnable to set up port!");
System.exit(1);
}
do {
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler handler = new ClientHandler(client);
handler.start();
}while (true);
}
}
class ClientHandler extends Thread
{
private Socket client;
private Scanner input;
private PrintWriter output;
public static Vector<Personnel> ClientList;
public ClientHandler(Socket socket) {
client = socket;
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(),true);
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public void run() {
String received;
String nekname;
nekname = input.nextLine();
ClientList.add(new Personnel(nekname,client));
try{
for(Personnel person:ClientList){
PrintWriter out = new PrintWriter(person.getLink().getOutputStream(),true);
out.println(nekname + " has entered the chatroom");
}
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
do {
received = input.nextLine();
try{
for(Personnel person:ClientList){
PrintWriter out = new PrintWriter(person.getLink().getOutputStream(),true);
out.println(nekname + ": " + received);
}
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}while (!received.equals("Bye") || !received.equals("bye"));
try { if (client!=null) {
for(Personnel person:ClientList){
PrintWriter out = new PrintWriter(person.getLink().getOutputStream(),true);
out.println(nekname + " has left the chatroom");
}
System.out.println("Closing down connection...");
client.close(); }
}
catch(IOException ioEx) {
System.out.println("Unable to disconnect!");
}
}
}
class Personnel{
private String nickname;
private Socket link;
public Personnel(String name,Socket l){
nickname = name;
link = l;
}
public String getName(){
return nickname;
}
public Socket getLink(){
return link;
}
}
任何幫助嗎?
請添加您收到的錯誤消息/異常。 – Alexander
什麼服務器?版?添加堆棧跟蹤。 –
歡迎來到SO。您的代碼很容易通過檢查_this time_進行調試,但對於將來的帖子,請記住發佈_complete_堆棧跟蹤(格式與代碼相同),並指出異常指向的代碼中的行。如果異常處於庫代碼中,請在您的代碼中找到最靠近堆棧頂部_is_的點,並標識_that_行。包括_you_要求的任何其他信息是有人將問題帶給你的。 –