Java客户端 - 服务器错误

时间:2016-03-27 22:47:09

标签: java networking nullpointerexception server client

我已经制作了一台服务器和客户端,在另一台服务器和客户端之间发送数据但是不起作用,我不知道为什么......

早一点,我收到服务器的错误消息:

  

java.net.SocketException:Broken pipe

现在我在第23行的客户端有空指针异常:

  

显示java.lang.NullPointerException

     

在chat.Client.sendData(Client.java:23)

这是我的代码:

服务器

public class Server {

    private ServerSocket server;
    public Socket socket;

    public Server() {
        try {
            this.server = new ServerSocket(Port_and_address.PORT);
            this.socket = server.accept();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String reciveData() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        String result = (String) ois.readObject();
        ois.close();
        return result;
    }

    public void writeData(String message) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(message);
        oos.close();
    }

    public void closeSocket() throws IOException {
        socket.close();
    }

    public static void main(String args[]) throws IOException, ClassNotFoundException {
        while (true) {
            System.out.println("Waiting for client request");
            Server server = new Server();
            System.out.println(server.reciveData());
            server.writeData("TEST SERVER");
            server.closeSocket();
        }
    }
}

客户端

public class Client extends Thread {

    Socket socket;

    public void Client() {
        try {
            this.socket = new Socket("localhost", Port_and_address.PORT);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void sendData(String message) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(message);
    }

    public String reciveData() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        ois.close();
        return (String) ois.readObject();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Client client = new Client();
        client.sendData("TEST CLIENT");
        System.out.println(client.reciveData());
    }
}

由于某种原因,该行给出了空指针异常:

    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

所以,如果你们中的任何人都知道我在这里做错了什么,请告诉我。 最后,我希望有一台服务器如何从任何客户端接收任何消息并对其进行响应,理论上我可以拥有无​​限数量的客户端如何发送消息。

寻求帮助:)

0 个答案:

没有答案