我得到了一个N​​ullPointerException并且我找不到问题

时间:2014-09-12 03:36:10

标签: java multithreading nullpointerexception messaging instant

'此代码可能存在多个问题,但我无法解决此第一个错误。我是一个新手,这项任务超出了我的想法。看了将近两个星期,我很绝望。任何帮助将不胜感激。在我尝试在服务器的textField中输入内容并按下回车之前,它不会给出错误。代码编译,但给出:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Server$1.actionPerformed(Server.java.71).

以下是代码:

import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Server extends JFrame {
//Global variables
private static ServerSocket serverSocket = null;
private static Socket connection = null;
private static PrintStream output = null;
private static BufferedReader input = null;
public static ArrayList<threadFromClient> clientList = new ArrayList<threadFromClient>();
private static  JTextField textField;
private static JTextArea msgWindow;
private static int port = 3333;

//Main program
public static void main(String[] args){
    Server server = new Server();
    if(args.length < 1){
        displayMsg("Usage: java Server <port> \n" + "Now using port number=" + port);
    }else{
        port = Integer.valueOf(args[0]).intValue();
    }
    server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    try{
        serverSocket = new ServerSocket(port);
        allowInput(true);
    }catch(EOFException e){
        displayMsg("Client terminated connection");
    }catch(IOException ioe){
        displayMsg(ioe.getMessage());
    }

    //Create a client socket for each connection and pass it to a new client thread
    while(true){
        try{
            connection = serverSocket.accept();

            for(int i = 0; i< clientList.size();i++){
                if(clientList.get(i) == null){
                    (clientList.set(i, new threadFromClient(connection,clientList))).start();
                    break;
                }
            }
            if(clientList.size() == 100){
                PrintStream os = new PrintStream(connection.getOutputStream());
                displayMsg("Server too busy.");
                os.close();
                connection.close();
            }
        }catch(Exception e){
            displayMsg(e.getMessage());
        }
    }

}//end main()

public Server(){
    super("Messenger Server");
    textField = new JTextField();
    textField.setEditable(false);
    textField.addActionListener(
        new ActionListener(){
            public void actionPerformed(ActionEvent e){
                String event = e.getActionCommand();
                output.println(event);
                output.flush();
                msgWindow.append(event);
                textField.setText("");              
            }
        }
    );
    add(textField, BorderLayout.NORTH);
    msgWindow = new JTextArea();
    add(new JScrollPane(msgWindow));
    setSize(500,350);
    setVisible(true);
}
//Enable textField
private static void allowInput(boolean bool){
    SwingUtilities.invokeLater(
        new Runnable(){
            public void run(){
                textField.setEditable(true);
            }
        }
    );
}//end allowInput()

//Sends msg to the client
private static void sendMsg(String msg){
        output.println("Server: " + msg);
        output.flush();
        displayMsg("\n Server:" + msg);
}//end sendMsg()

//Updates msgWindow
private static void displayMsg(final String msg){
    SwingUtilities.invokeLater(
        new Runnable(){
            public void run(){
                msgWindow.append(msg);
            }
        }
    );
}//end displayMsg()

}//end Server class

import java.io.*;
import java.net.*;
import java.util.ArrayList;


public class threadFromClient extends Thread implements Runnable{
private String userName;
private BufferedReader input;
private PrintStream output;
private Socket connection;
private ArrayList<threadFromClient> threads;


public threadFromClient(Socket connection, ArrayList<threadFromClient> threads){
    this.connection = connection;
    this.threads = threads;
}//end constructor

public void run(){
    ArrayList<threadFromClient> threads = this.threads;
    try{
        //create input and output for client
        output = new PrintStream(connection.getOutputStream());
        output.flush();
        input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        output.println("\n Streams are now connected! \n");
        //communicating
        String name;
        while(true){
            output.println("Enter your name");
            name = input.readLine().trim();
            if(name.indexOf('@') == -1){
                break;
            }else{
                output.println("No @ allowed");
            }
        }

        //welcome the new client
        output.println("Welcome " + name + "!");
        synchronized (this){
            for(int i = 0;i < threads.size();i++){
                if(threads.get(i) != null && threads.get(i) == this){
                    userName = "@" + name;
                    break;
                }
            }
            for(int i = 0;i<threads.size();i++){
                if(threads.get(i) != null && threads.get(i) != this){
                    threads.get(i).output.println("A new user " + name + " entered the network");
                }
            }
        }
        //starting conversation
        while(true){
            String line = input.readLine();
            if(line.equals("END")) break;
            //if the message is private send it to the given client
            if(line.startsWith("@")){
                String[] words = line.split("\\s", 2);
                if (words.length > 1 && words[1] != null) {
                    words[1] = words[1].trim();
                    if (!words[1].isEmpty()) {
                        synchronized (this) {
                            for (int i = 0; i < threads.size(); i++) {
                                if (threads.get(i) != null && threads.get(i) != this
                                        && threads.get(i).userName != null
                                        && threads.get(i).userName.equals(words[0])) {
                                        threads.get(i).output.println("<" + name + "> " + words[1]);
                                        /*
                                         * Echo this message to let the client know the private
                                         * message was sent.
                                         */
                                        this.output.println(">" + name + "> " + words[1]);
                                        break;
                                }
                            }
                        }
                    }
                }
            }else {
              /* The message is public, broadcast it to all other clients. */
              synchronized (this) {
                for (int i = 0; i < threads.size(); i++) {
                  if (threads.get(i) != null && threads.get(i).userName != null) {
                    threads.get(i).output.println("<" + name + "> " + line);
                  }
                }
              }
            }
          }
          synchronized (this) {
            for (int i = 0; i < threads.size(); i++) {
              if (threads.get(i) != null && threads.get(i) != this
                  && threads.get(i).userName != null) {
                threads.get(i).output.println("*** The user " + name
                    + " is leaving the chat room !!! ***");
              }
            }
          }
          output.println("*** Bye " + name + " ***");

          /*
           * Clean up. Set the current thread variable to null so that a new client
           * could be accepted by the server.
           */
          synchronized (this) {
            for (int i = 0; i < threads.size(); i++) {
              if (threads.get(i) == this) {
                threads.set(i, null);
              }
            }
          }
          /*
           * Close the output stream, close the input stream, close the socket.
           */
          input.close();
          output.close();
          connection.close();
    }catch(Exception e){
        output.println(e.getMessage());
    }
}//end run()

} //结束threadFromClient类

0 个答案:

没有答案