"java.io.StreamCorruptedException: invalid type code: AC"- Error found while running the client code from the server-client java program

13,222

Solution 1

You are double opening an ObjectOutputStream on the same socket in the Server class which is causing special headers to be sent twice.

1: openSockets last line outputToClient = new ObjectOutputStream(clientSocket.getOutputStream());

2: writeToSocket first line outputToClient = new ObjectOutputStream(clientSocket.getOutputStream());

Remove whichever one you want and it should work just fine.

As for the nullpointer you are now receiving I have a feeling that video is null in the client. In the code you have posted that would make sense because in the server you never create a video array and as such the client is just receiving null.

Solution 2

This error is caused by using more than one ObjectOutputStream on the same socket. Use the same ObjectOutputstream and ObjectInputStream for the life of the socket, at both ends. Same goes for most other stream and reader/writer types, except that the consequences of not doing so are usually even more mysterious.

Share:
13,222
Atif S.
Author by

Atif S.

Innovation and practical thinking is what important,creating a brighter future for us and for the world is what i believe in. "The concept of big ideas are secretly hidden in small ideas. What we are trying to achieve is getting bigger things done by things around us to create a dynamically implicit scenario where people realize the potential behind the hard work and effort that is put into it"-Atif Syed "To create a dynamic equation which satisfies the hunger for quantum mechanics which in turn can be applied for real time use requires something which sparks and triggers our imagination and the Schrödinger equation is the perfect example of this!"- Atif Syed "If we consider electron to act as a wave rather than a particle, the entire atom can be represented by wave functions and perhaps the Schrödinger's Equation can be applied to know the uncertainty of the electron moving in real and complex planes, it would be quite amazing if we can do this, it would also add to our discoveries in quantum computing and mechanics" - Atif Syed "Everyone is good at Math and Physics its just they don't realize it"- Atif Syed "Quantum Entanglement is kind of romantic. Two particles with entangled fate, no matter the distance between them. Yet the mystery of their fate is necessary. When you determine the value of one of them, the wave function collapses and entanglement ends" "Successful people do what unsuccessful people don't. They wake up :) WAKE UP and make good use of your life. Gain knowledge, impart knowledge, help people, do charity, strive for the betterment of your family, for your friends and for yourself. Its never too late :)" "The same spiritual fulfillment that people find in religion can be found in science by coming to know, if you will, the mind of God and science gives a new wave of reason by skeptically interrogating the universe and its working. The beauty of living is not the atoms that go into it but its the way the atoms are put together :)"

Updated on June 04, 2022

Comments

  • Atif S.
    Atif S. almost 2 years

    Well, I am trying to read a .xml file from the XMLParser so basically I want to read the XML files and print it out from the server to the client, but while running the client code i am getting:

    java.io.StreamCorruptedException: invalid type code: AC
    

    The Client code is:

    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.List;
    
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    
    import server.Video;
    import server.VideoFile;
    
    @SuppressWarnings("serial")
    public class Client extends JFrame{
        Container contentPane;
        @SuppressWarnings("rawtypes")
        JComboBox selectionBox;
    
        List<Video> video;
        List<VideoFile> videoFile;
    
        Socket serverSocket;
        String host = "127.0.0.1";
        int port = 1176;
        ObjectInputStream inputFromServer;
        ObjectOutputStream out;
    
        public Client() throws Exception {
            // line 41 below
                setupGUI();
    
            System.out.println("Reading the XML File");
            MyXMLReader reader = new MyXMLReader();
            //video = reader.getList("videoList.xml");
            System.out.println("Finished reading");
        }
    
        public void openSocket() throws UnknownHostException, IOException {
             /** Obtain an address object of the server */
            serverSocket = new Socket("localhost", port);
            System.out.println("Connected to localhost in port: " + port);
            out = new ObjectOutputStream(serverSocket.getOutputStream());
            //out.flush();
            inputFromServer = new ObjectInputStream(serverSocket.getInputStream());
    
        }
    
        @SuppressWarnings("unchecked")
        public void getListFromSocket() throws IOException, ClassNotFoundException {
            try{
            video = (List<Video>)inputFromServer.readObject();
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
            //serverSocket.close();
        }
        public void runClient() throws Exception {
    
                try {
                    openSocket();
                    getListFromSocket();
                    serverSocket.close();
                    setupGUI();
                    } catch (UnknownHostException e) {
                    System.out.println("Don't know about host : " + host);
                    System.exit(-1);
                    } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("Couldn't open I/O connection : " + host + ":" + port);
                    System.exit(-1);
                    } catch (ClassNotFoundException e) {
                    System.out.println("Class definition not found for incoming object.");
                    e.printStackTrace();
                    System.exit(-1);
                }
    
        }
    
        @SuppressWarnings({ "unchecked", "rawtypes" })
        private void setupGUI() throws Exception{
            setTitle("A Client");
            setSize(600, 400);
            setVisible(true);
            contentPane = getContentPane();
            contentPane.setLayout(new BorderLayout());
    
                runClient();
    
            // line 105 below
            String [] selectionListData = new String[video.size()];
            for (int i = 0; i < video.size(); i++) {
            selectionListData[i] = video.get(i).getFilename();
            selectionListData[i] = video.get(i).getID();
            selectionListData[i] = video.get(i).getTitle();
            System.out.println(selectionListData);
            }
            selectionBox = new JComboBox(selectionListData);
            selectionBox.setSelectedIndex(0);
            add(selectionBox, BorderLayout.NORTH);
            selectionBox.addActionListener((ActionListener) this);
    
            validate();
        }
    
        public void actionPerformed(ActionEvent e) {
            @SuppressWarnings("rawtypes")
            JComboBox comboBox = (JComboBox)e.getSource();
            String selectedTitle = (String)comboBox.getSelectedItem();
            System.out.println("Selected title : " + selectedTitle);
            }
    
    
        public static void main(String[] args) throws IOException, Exception {
                // line 127 below
            new Client();
    
        }
    
    }
    

    The full error is:

        Connected to localhost in port: 1176
        java.io.StreamCorruptedException: invalid type code: AC
        at java.io.ObjectInputStream.readObject0(Unknown Source)
        at java.io.ObjectInputStream.readObject(Unknown Source)
        at client.Client.getListFromSocket(Client.java:61)
        at client.Client.runClient(Client.java:72)
        at client.Client.<init>(Client.java:40)
        at client.Client.main(Client.java:124)
    

    Can anyone give a fix to this, I am sure its something small but I can't figure it out though.

    Thanks

    EDIT: The server code is:

    package server;
    
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.List;
    import java.lang.*;
    
    @SuppressWarnings("unused")
    public class Server extends Thread implements Runnable{
        List<Video> video;
        static String TimeStamp;
        //Socket Declerations
        ServerSocket serverSocket;
        int port = 1176;
        //String host = "localhost";
        Socket clientSocket;
        ObjectOutputStream outputToClient;
    
    
    
        public Server() {
            Thread();
            System.out.println("Reading the XML File");
            MyXMLReader reader = new MyXMLReader();
            //video = reader.getList("videoList.xml");
            System.out.println("Finished reading");
        }
    
        public void openSockets() throws IOException {
            try {
                serverSocket = new ServerSocket(port);
                System.out.println("Socket Connection Established....");
            } catch (IOException e) {
                System.out.println("Could not listen on port : " + port);
                System.exit(-1);
            }
            TimeStamp = new java.util.Date().toString();
            System.out.println("Opened socket on : " + port + ", waiting for client. " + TimeStamp);
    
            try {
                clientSocket = serverSocket.accept();
                //System.out.println("Sending to Client.....");
                } catch (IOException e) {
                System.out.println("Could not accept client.");
                System.exit(-1);
                }
                outputToClient = new ObjectOutputStream(clientSocket.getOutputStream());
        }
        public void writeToSocket() throws IOException {
            outputToClient = new ObjectOutputStream(clientSocket.getOutputStream());
            outputToClient.writeObject(video);
            System.out.println(outputToClient);
        }
    
        public void Thread() {
            Thread socketThread;
            socketThread = new Thread("Socket") {
            public void run() {
                try {
                    openSockets();
                    writeToSocket();
                    clientSocket.close();
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("Error on sockets connection.");
                    e.printStackTrace();
                }
            }
    };
    socketThread.start();
    }
    
        public static void main(String[] args) throws IOException {
            new Server();
            //new Thread();
    
    
        }
    
    }
    

    EDIT: New error after deleting the duplicate entry:

    Exception in thread "main" java.lang.NullPointerException
        at client.Client.setupGUI(Client.java:105)
        at client.Client.<init>(Client.java:41)
        at client.Client.main(Client.java:127)
    
    • Krrose27
      Krrose27 almost 12 years
      The issue may actually be in the Server. Can you post its code?
    • Atif S.
      Atif S. almost 12 years
      I have just added the server code above.
    • Krrose27
      Krrose27 almost 12 years
      In client can you add a comment on line 105, 41, and 127? When I toss it in something that has line numbers nothing is matching up with what could be causing a nullpointer.
    • Atif S.
      Atif S. almost 12 years
      I have just edited the client code and added comments for lines 105,41,127.
    • Krrose27
      Krrose27 almost 12 years
      please see my updated answer.
    • Atif S.
      Atif S. almost 12 years
      I understand that but the point of this one is that while creating a server-client app, the client should be able to select videos so technically the videoList.xml should not be in the client package so as to test if the server is sending the contents of the video to the client to view it, so if i am getting a null pointer which means that the server is not really sending the video in a serialized manner. I also implemented "Serializable" in the Video class but it didn't help much.
    • Krrose27
      Krrose27 almost 12 years
      SO is yelling at me for so many comments. It says we need to move to a chat but you dont have enough rep. So this will be my last reply. MyXMLReader reader = new MyXMLReader(); //video = reader.getList("videoList.xml"); You have video commented out. Maybe that shouldnt be. IDK. But you need to populate the List<Video> in the Server before sending it to the client.
  • Atif S.
    Atif S. almost 12 years
    Oh! Thanks for pointing it out. There is a new issue/error. While running the client the following a new error is seen. I have added in the question above. I think its not able to read the file but when I am running the XML Parser in the Client code, the XML Parse runs but in "String [] selectionListData = new String[video.size()];" its not able to get its size
  • user207421
    user207421 almost 12 years
    @AtifS. So you are deferencing a null reference variable at MEMEClient.java line 105. As you haven't posted that code it is impossible for anyone to help you further. You should be able to sort out an NPE by yourself but if not you would need to post it and the code concerned as a new question.
  • user207421
    user207421 almost 12 years
    He can't 'remove whichever one you want'. He must remove the one in the writeToSocket() method, and store the other one in a member variable. Otherwise he will still get a new OOS per write, and still have the same problem.
  • Atif S.
    Atif S. almost 12 years
    Thanks, I have removed that. It was not supposed to be there I was experimenting, the first error was caused by the duplicate entry pointed out by @Krroae27. Can you see the edited question for the null pointer error and see any obvious errors I made in the code?
  • Krrose27
    Krrose27 almost 12 years
    @EJP actually the way he has it written it doesn't matter. He closes it after one call. So unless if he is planning to run it differently then what he has he can remove either one.
  • Atif S.
    Atif S. almost 12 years
    @EJP- It is the same code, I pasted the wrong filename before which might have caused confusion. Its the Client.java code as before
  • user207421
    user207421 almost 12 years
    @AtifS. You still haven't told us which is line 105, but, as I said, you are really expected to sort out NullPointerExceptions on your own. Everything you need to do so is in the stack trace. Doing it this way via a forum is just wasting time.
  • user207421
    user207421 over 6 years
    No. Professional programmers are expected to be able to sort out NPEs by themselves. If you had asked that as a question it woudl have been closed as a duplicate almost instantaneously.