“java.io.StreamCorruptedException:无效类型代码:AC”- 从服务器-客户端 java 程序运行客户端代码时发现错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10475603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:13:22  来源:igfitidea点击:

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

javasocketsclient

提问by Atif S.

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:

好吧,我正在尝试从 XMLParser 读取 .xml 文件,所以基本上我想读取 XML 文件并将其从服务器打印到客户端,但是在运行客户端代码时我得到:

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)

回答by Krrose27

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

您在 Server 类中的同一个套接字上打开了一个 ObjectOutputStream,这导致特殊标头被发送两次。

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

1:openSockets最后一行outputToClient = new ObjectOutputStream(clientSocket.getOutputStream());

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

2:writeToSocket第一行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.

至于您现在收到的空指针,我感觉客户端中的视频为空。在您发布的代码中,这是有道理的,因为在服务器中您从不创建视频数组,因此客户端只是接收空值。

回答by user207421

This error is caused by using more than one ObjectOutputStreamon the same socket. Use the same ObjectOutputstreamand ObjectInputStreamfor 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.

此错误是由ObjectOutputStream在同一个套接字上使用多个引起的。在插座的两端使用相同的ObjectOutputstreamObjectInputStream终生的。大多数其他流和读取器/写入器类型也是如此,只是不这样做的后果通常更加神秘。