0

每当我运行聊天服务器时,它都会一直工作,直到客户端连接,然后我在 connections.add(socket); 处得到一个空指针异常;它崩溃了,然后每次我运行它时都会发生这种情况。我知道我的客户端很好,因为几个月前我看了一个关于如何做到这一点的教程,并且该服务器与我的客户端一起工作而不会崩溃

private static ServerSocket server;
private static Socket socket;
private static Scanner input;
private static PrintWriter output;

private static final int port = 444;
private static String message;
private static ArrayList<Socket> connections;
private static Server serverClass;

public Server() {

    message = "";
    connections = new ArrayList<Socket>();
    serverClass = new Server();

}

public void run() {

    try {

        try {

            input = new Scanner(socket.getInputStream());
            output = new PrintWriter(socket.getOutputStream());

            while(true) {

                checkConnection();

                if(!input.hasNext()) {

                    return;

                }

                message = input.nextLine();
                System.out.println("Client said: " + message);

                for(int i = 1; i <= connections.size(); i++) {

                    Socket tempSock = (Socket) connections.get(i - 1);
                    output.println(message);
                    output.flush();

                }

            }

        }
        finally {

            socket.close();

        }

    }
    catch(Exception e) {

        System.out.print(e);

    }

}

public void checkConnection() throws IOException {

    if(!socket.isConnected()) {

        for(int i = 1; i <= connections.size(); i++) {

            if(connections.get(i) == socket) {

                connections.remove(i);

            }

        }

        for(int i = 1; i <= connections.size(); i++) {

            Socket disconnectedUser = (Socket) connections.get(i - 1);
            System.out.println(disconnectedUser + " has Disconnected!");

        }

    }

}

public static void main(String[] args) throws IOException{

    try {

        server = new ServerSocket(port);
        System.out.println("Waiting for Clients... ");

        while(true) {

            socket = server.accept();
            connections.add(socket);
            System.out.println("Client connected from: " + socket.getLocalAddress().getHostName());

            Thread thread = new Thread(serverClass);
            thread.start();

        }

    }
    catch(Exception e) {

        e.printStackTrace();

    }

}
4

1 回答 1

3

如果你得到一个 NPEconnections.add(socket),只能是因为它connections是空的。是这样的,因为您还没有构造Server: 的实例,而是尝试从main().您调用的唯一位置new Server()在构造函数内部执行它的所有代码,Server,而您显然从未执行过,因为您将得到StackOverflowError从无限递归。

这段代码真是一团糟:

  • 修复无限递归
  • Server在你的main()方法中构造一个实例
  • 使connections非静态
  • socket在接受循环中创建一个局部变量
  • 修复循环以从 0 迭代到connections.size()-1

然后再试一次。

于 2013-08-19T01:09:19.260 回答