简体   繁体   中英

Java ObjectInputStream(socket.getInputStream()) catches null object

I'm making a client server couple. My client connects to server very well and it creates ObjectInputStream(socket.getInputStream()) over the socket, from server to client and vice versa. Then for some mystical reason my ObjectInputStream of the server somehow catches a null object. Client haven't sent anything over the socket (I did put / .. / over the object send method to make this sure and even System.out.printed all the objects sent earlier) Server catches that mystical object only once, and after that all the objects sent By client work just as they should..

class ClientThread extends Thread {
        //The socket where to listen/talk
        Socket socket;
        ObjectInputStream sInput;
        ObjectOutputStream sOutput;
        InputStream fInput;
        OutputStream Output;
        //my unique id (easier for deconnection)
        int id;
        //Objects that we will be receiving
        Incomingdata datain;
        //the date we connect
        String date;
        Player player;
        boolean Connected = false;

        //Constructor
        ClientThread(Socket socket){
            id = uniqueId++;
            this.socket = socket;
            try{
                sOutput = new ObjectOutputStream(socket.getOutputStream());
                sInput = new ObjectInputStream(socket.getInputStream());
                Output = socket.getOutputStream();
            } catch (Exception e){
                System.out.println("Couldn't create Input/Output streams");
            }
            date = new Date().toString();
        }

        // what will run forever
        public void run() {
            // to loop until LOGOUT
            Connected = true;
            while(Connected) {
                try {
                    datain = (Incomingdata) sInput.readObject(); //<--- this catches the mystical null! Even if nothing is sent over the socket?
                }
                catch (IOException e) {
                    TextArea.AddLine("Exception reading Streams: " + e);
                    break;              
                }
                catch(ClassNotFoundException e2) {
                    break;
                }

You can only receive a null if you send a null.

(There is a widespread misconception that readObject() returns null at end of stream. It doesn't.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM