Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java套接字I/O流空指针异常_Java_Sockets - Fatal编程技术网

Java套接字I/O流空指针异常

Java套接字I/O流空指针异常,java,sockets,Java,Sockets,我有一个简单的客户机和服务器,我写它是为了教会自己一点网络。它的设置方式是我有一个主服务器类来处理创建/销毁套接字,还有一个ConnectionRead类来表示每个连接(每个连接都有自己的线程)。客户端非常简单 问题在于在ConnectionRead类中创建输入/输出流。我不确定到底是什么问题,但当简单测试客户端尝试连接时,它会崩溃,这给了我: ~~MMO Server Alpha .1~~ Constructed Server Server Initialized, preparing to

我有一个简单的客户机和服务器,我写它是为了教会自己一点网络。它的设置方式是我有一个主服务器类来处理创建/销毁套接字,还有一个ConnectionRead类来表示每个连接(每个连接都有自己的线程)。客户端非常简单

问题在于在ConnectionRead类中创建输入/输出流。我不确定到底是什么问题,但当简单测试客户端尝试连接时,它会崩溃,这给了我:

~~MMO Server Alpha .1~~
Constructed Server
Server Initialized, preparing to start...
Server preparing to check if it should be listening...
Server should be listening, continuing as planned.
ServerSocket passed to ConnectionThread: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=6969]
Constructing ConnectionThread.
Socket[addr=/10.0.1.10,port=55332,localport=6969]
ConnectionThread constructed.
Exception in thread "main" java.lang.NullPointerException
    at ConnectionThread.init(ConnectionThread.java:65)
    at Server.listen(Server.java:98)
    at Server.start(Server.java:62)
    at Server.main(Server.java:122)
ConnectionThread added to queue.
Establishing in and out streams:
null
以下是课程(为简洁起见进行了修订):

或者,这里是测试客户机:

public class TestClient {
    static PrintWriter out;
    BufferedReader in;
    public final int PORT = 6969;
    Socket socket = null;
    InetAddress host = null;

    public TestClient() {
        out = null;
        in = null;
        socket = null;
        host = null;



    }



    public void connectToServer() {
        System.out.println("Connecting to server...");
        try {
            host = InetAddress.getLocalHost();
            socket = new Socket(host.getHostName(), PORT);
        }
        catch (Exception e) {
            System.out.println("Error establishing host/socket");
            System.exit(1);
        }




        try {
            System.out.println("Establishing I/O Streams");
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        catch (Exception e) {
            System.out.println("Error establishing in/out streams");
            System.exit(1);
        }
    }


    public static void main(String[] args) {
        System.out.println("~~TestClient Alpha .1~~");
        TestClient c = new TestClient();
        c.connectToServer();
        System.out.println("Should be connected to server. Sending test message...");
        while (true) {
            System.out.println("here");
            out.println("Hello there");
        }

    }

}

ConnectionRead构造函数中的“socket”变量不应为本地变量。它正在隐藏成员变量


通常在listen()循环中调用accept(),并将接受的套接字传递给ConnectionThread。

ConnectionThread的构造函数中的“socket”变量不应是本地变量。它正在隐藏成员变量


通常在listen()循环中调用accept(),并将接受的套接字传递给ConnectionThread。

因为,在ConnectionThread构造函数中,您认为您正在将值分配给
socket
字段,但实际上您正在将值分配给
socket
方法变量,因此,
socket
字段保持为空,在
init()
中,您将
socket
视为空。

,因此,
socket
字段保持为空,在
init()
中,您会看到
socket
为空。

除了EJP回答:您没有提供connectionRead.run()方法,但我假设您将在
run()
方法中使用字段
in
out
socket
。由于这些字段没有标记为
volatile
final
,这取决于您的运气和计算机上的内核数,因此您还可能在run()方法中获得NullPointerException

这是因为新变量值可能不会在缓存之间传播,并且新线程将不会看到更改的值


这个可能问题的解释在这里-

除了EJP回答:您没有提供connectionRead.run()方法,但我假设您将在
run()
方法中使用
In
out
socket
字段。由于这些字段没有标记为
volatile
final
,这取决于您的运气和计算机上的内核数,因此您还可能在run()方法中获得NullPointerException

这是因为新变量值可能不会在缓存之间传播,并且新线程将不会看到更改的值


这个可能问题的解释就在这里-

哦,老兄。多大的疏忽啊。非常感谢你指出这一点。StackOverflow的善良和乐于助人从未停止让人惊讶。哦,伙计。多大的疏忽啊。非常感谢你指出这一点。StackOverflow的善良和帮助从未停止过。谢谢你,没有意识到线程开始创建之前发生过。谢谢你,没有意识到线程开始创建之前发生过。
public class ConnectionThread implements Runnable {
    boolean shouldBeListening = true;
    boolean isThereAnUnsentOutgoingMessage = false;
    String outgoingMessage = "OUTGOING UNINITIALIZED";
    boolean IsThereAnUnsentIncomingMessage = false;
    String incomingMessage = "INCOMING UNITIALIZED";
    boolean isInitialized = false;
    PrintWriter out;
    BufferedReader in;

    String currentInputMessage = "Test Input Message from the Server ConnectionThread";
    String previousInputMessage = null;


    Socket socket;





    public ConnectionThread(ServerSocket s) {
        System.out.println("ServerSocket passed to ConnectionThread: " + s);
        /*
         * The purpose of the constructor is to establish a socket
         * as soon as possible. All transmissions/logic/anything else
         * should happen in init() and/or run().
         */
        System.out.println("Constructing ConnectionThread.");
        try {
        Socket socket = s.accept();
        System.out.println(socket);
        }
        catch (IOException e) {
            System.out.println("Error in ConnectionThread constructor");
            System.exit(1);
        }
    }




    public void init() {
        /*
         * Everything should be set up here before run is called.
         * Once init is finished, run() should be set to begin work.
         * This is to ensure each packet is efficiently processed.
         */
        try {
            System.out.println("Establishing in and out streams:");
            System.out.println(socket);
            out = new PrintWriter(socket.getOutputStream(), true);
            System.out.println("ConnectionThread: Output Stream (PrintWriter) Established");

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("ConnectionThread: InputStream (BufferedReader) Established");
        }
        catch (IOException e) {
            System.out.println("Error in ConnectionThread method Init.");
            System.exit(1);
        }



        isInitialized = true;
    }
public class TestClient {
    static PrintWriter out;
    BufferedReader in;
    public final int PORT = 6969;
    Socket socket = null;
    InetAddress host = null;

    public TestClient() {
        out = null;
        in = null;
        socket = null;
        host = null;



    }



    public void connectToServer() {
        System.out.println("Connecting to server...");
        try {
            host = InetAddress.getLocalHost();
            socket = new Socket(host.getHostName(), PORT);
        }
        catch (Exception e) {
            System.out.println("Error establishing host/socket");
            System.exit(1);
        }




        try {
            System.out.println("Establishing I/O Streams");
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        catch (Exception e) {
            System.out.println("Error establishing in/out streams");
            System.exit(1);
        }
    }


    public static void main(String[] args) {
        System.out.println("~~TestClient Alpha .1~~");
        TestClient c = new TestClient();
        c.connectToServer();
        System.out.println("Should be connected to server. Sending test message...");
        while (true) {
            System.out.println("here");
            out.println("Hello there");
        }

    }

}