Java Simple Chat Server和Client引发空指针异常

时间:2019-07-05 07:41:39

标签: java network-programming inputstream outputstream

我正在跟踪Kathy Sierra和Bert Bates的Head First Java。在书中,他们构建了一个简单的聊天服务器和客户端。因此,我参考了他们的代码,并为服务器和客户端编写了类似的代码。因此,您在一个终端中运行服务器,而在另一终端中运行客户端。客户端通过IP地址127.0.0.1和端口5000连接到套接字。客户端具有一个JTextField可以将String消息发送到服务器,还有一个JTextArea可以接收和显示来自服务器的String消息。该服务器能够使用针对不同客户端的不同线程来处理多个客户端。当服务器从任何客户端收到消息时,它将在其终端上打印“ read-消息”。我在下面为服务器和客户端提供了代码-

聊天服务器代码-

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

public class ChatServer{
    ArrayList clientOutputHandlers = new ArrayList();

    public void go(){
        try{
            ServerSocket servSock = new ServerSocket(5000);

            while(true){
                Socket sock = servSock.accept();

                PrintWriter writer = new PrintWriter(sock.getOutputStream());
                clientOutputHandlers.add(writer);

                Thread clientHandlerThread = new Thread(new ClientHandler(sock));
                clientHandlerThread.start();

                System.out.println("New Client Connected!");
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public class ClientHandler implements Runnable{

        BufferedReader reader;
        Socket clientSocket;

        public ClientHandler(Socket sock){
            clientSocket = sock;
            try{
                InputStreamReader streamReader = new InputStreamReader(clientSocket.getInputStream());
                reader = new BufferedReader(streamReader);
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }

        public void run(){
            String message = null;
            try{
                InputStreamReader streamReader = new InputStreamReader(clientSocket.getInputStream());
                reader = new BufferedReader(streamReader);

                while( (message = reader.readLine()) != null){
                    System.out.println("read - "+message);
                    broadcast(message);
                }
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }

    public void broadcast(String message){
        Iterator it = clientOutputHandlers.iterator();
        while(it.hasNext()){
            try{
                PrintWriter writer = (PrintWriter) it.next();
                writer.println(message);
                writer.flush();
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        ChatServer cs = new ChatServer();
        cs.go();
    }
}

聊天客户端代码-

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

public class ChatClient{
    JTextArea incoming;
    JTextField outgoing;
    JButton sendButton;
    Socket socket;
    PrintWriter writer;
    BufferedReader reader;

    public void setUpGui(){
        JFrame frame = new JFrame("Chat Client");
        JPanel northPanel = new JPanel();
        northPanel.setBorder(BorderFactory.createEmptyBorder(20,0,0,0));

        outgoing = new JTextField(40);
        outgoing.addActionListener(new OutgoingListener());
        sendButton = new JButton("Send");
        sendButton.addActionListener(new SendListener());

        northPanel.add(outgoing);
        northPanel.add(sendButton);

        JPanel mainPanel = new JPanel();
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

        incoming = new JTextArea(20,40);
        Font incomingFont = new Font("sanserif", Font.BOLD, 16);
        incoming.setFont(incomingFont);
        JScrollPane scroller = new JScrollPane(incoming);
        scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        mainPanel.add(scroller);

        frame.getContentPane().add(BorderLayout.NORTH, northPanel);
        frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();

        Thread readThread = new Thread(new ReadMessages());
        readThread.start();
    }

    public void setUpNetwork(){
        try{
            socket = new Socket("127.0.0.1", 5000);

            writer = new PrintWriter(socket.getOutputStream());

            InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
            reader = new BufferedReader(streamReader);

            System.out.println("Connected! Ready to go\n");
            incoming.append("Connected! Ready to go"+"\n");
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public class SendListener implements ActionListener{
        public void actionPerformed(ActionEvent ev){
            String line = outgoing.getText();
            try{
                writer.println(line);
                writer.flush();
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
        }
    }

        public class OutgoingListener implements ActionListener{
        public void actionPerformed(ActionEvent ev){
            String line = outgoing.getText();
            try{
                writer.println(line);
                writer.flush();
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
        }
    }

    public class ReadMessages implements Runnable{
        public void run(){
            String line = null;
            try{
                while( (line = reader.readLine()) != null){
                    System.out.println("read " + line);
                    incoming.append(line+"\n");
                }
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        ChatClient cc = new ChatClient();
        cc.setUpGui();
        cc.setUpNetwork();
    }
}

因此,聊天服务器可以编译,但终端上会显示这些消息-

Note: ChatServer.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

聊天客户端编译没有任何错误。

在一台终端中运行服务器后。我打开另一个终端并运行聊天客户端,但它给出了以下异常-

java.lang.NullPointerException
        at ChatClient$ReadMessages.run(ChatClient.java:101)
        at java.lang.Thread.run(Unknown Source)

,但GUI显示正常。 现在,当我在“客户端”文本字段中键入消息时,服务器终端会显示它已读取一条消息,但该消息未出现在客户端的文本区域。

所以你们中的任何一个都可以帮助我。是我的防火墙还是阻止某些东西。 idk我在编程方面几乎是个菜鸟。

0 个答案:

没有答案