0

我有两个可以相互配合使用的应用程序。一个是“服务器”类型的应用程序,它没有任何 GUI 界面并处理对数据库的查询并处理来自客户端的请求。另一个是“客户端”,主要是一个 GUI,供用户以结构化方式与数据库信息进行交互。

问题/麻烦/需要帮助

我遇到的问题是我可以成功地将一个对象(一个字符串 [])发送到服务器并且没有任何问题。客户端应用程序发送它,服务器应用程序接收它并成功处理它。

如果我尝试发送第二个 String[],则客户端编译数组并认为它已发送,但服务器从未收到 is(仅获取 null)并产生 IOException。

即使是包含完全相同数量的位置和完全相同格式和位置的完全相同文本的数组也是如此。

printStackTrace() 产生的错误是:

Java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0 (ObjectInputStream.java:1367)
at java.io.ObjectInputStream.readObject (ObjectInputStream.java:369)
at server.ConnectionThread.processClientRequests(ConnectionThread:204)
at server.ConnectionThread.processClientRequests(ConnectionThread:50)
at javalang.Thread.run(Thread.java:722) 

第 204 行的代码是读取 ObjectStream 的点:

String[] addArray = (String[]) ois.readObject();

ois 是一个 ObjectInputStream,初始化如下:

private ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

客户代码

用于将这些对象发送到服务器应用程序的客户端代码是:

ObjectToServer.writeObject(String[] var);
ObjectToServer.flush();
ObjectToServer.reset();

评论

对我来说没有意义的是,这种完全相同的代码格式用于通过 objectOutputStream 从 SERVER 成功发送多个 String[] 到 CLIENT 应用程序,而无需发送“null”

我已经谷歌搜索了这个,一切都无济于事。

如果可以的话,请有人帮忙!!

                             ADDITIONAL CODE

// CONNECTION THREAD IS ON SERVER APP, SETS UP STREAMS AND WAITS FOR MESSAGES FROM CLIENT
// HANDLES COMMUNICATION FROM CLIENT AND REST OF SERVER

public class ConnectionThread implements Runnable
{

    private Socket socket;
    private SystemCore core;
    //Streams for connections
    private InputStream is;
    private OutputStream os;
    //Writers and readers for communication of Strings
    private PrintWriter toClient;
    private BufferedReader fromClient;
    // Writers and readers for sending and receiving Objects between server and client.
    private ObjectInputStream ois = null;
    private ObjectOutputStream oos = null;
    //Protocol
    static final String CLIENT_QUITTING = "Exit";

    public ConnectionThread(Socket s, SystemCore aSysCore)
    {
        socket = s;

        // State of the SystemCore as taken from HelloServer
        core = aSysCore;
    }

    public void run()
    {
        try
        {
            openStreams();
            toClient.println(MESSAGE_TO_CLIENT);
            processClientRequests();
            closeStreams();
            this.socket.close();
        }
        catch (OptionalDataException ode )
        {
            System.out.println("OptionalDataException: ");
            System.out.println("length is: " + ode.length);
        }
        catch (IOException ioe)
        {
            System.out.println("IO trouble with a connection in ConnectionThread run() " + ioe.getMessage());
            ioe.printStackTrace();
        }
       catch (ClassNotFoundException cnf)
        {
            System.out.println("Class trouble with a connection in ConnectionThread run() " + cnf.getMessage());
            cnf.printStackTrace();
        }
        catch(ParseException pe)
        {
            System.out.println("Parse trouble with a connection in ConnectionThread run() " + pe.getMessage());
            pe.printStackTrace();
        } 
    }

    /**
     * Opens streams between the server and the client.
     *
     * @throws IOException
     */
    private void openStreams() throws IOException
    {
        final boolean AUTO_FLUSH = true;
        this.is = this.socket.getInputStream();
        this.fromClient = new BufferedReader(new InputStreamReader(is));
        this.os = this.socket.getOutputStream();
        this.toClient = new PrintWriter(os, AUTO_FLUSH);

        //Object streams.
        oos = new ObjectOutputStream(socket.getOutputStream());
        ois = new ObjectInputStream(socket.getInputStream());

        System.out.println("...Streams set up");
    }


    /**
     * Private method that accepts arguments from a client and executes the related
     * commands in the systemcore as long as the command passed from the client
     * is not CLIENT_QUITTING.
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private void processClientRequests() throws IOException, ClassNotFoundException, ParseException
    {
        String commandFromClient;
        commandFromClient = fromClient.readLine();
        while (!(commandFromClient.equals(CLIENT_QUITTING)))
        {
            if (commandFromClient.equals("addProjectPrepare"))
            {
                String[] addArray = (String[]) ois.readObject();
                core.addProjectPrepare(addArray);
            }
            if (commandFromClient.equals("editProjectPrepareDetails"))
            {
                String[] editArray = (String[]) ois.readObject();
                recruit.editProjectPrepareDetails(editArray);               
            }
        }
           commandFromClient = fromClient.readLine();
    }


**// CLIENT SIDE (User GUI) CODE THAT SENDS STRING[] TO THE SERVER**




public void saveAction()
    {
        // TEST TO SEE IF THE DATE ENTERED IS CORRECT FORMAT, IF NOT NO SAVE OCCURRS

    boolean parsedOk = false;

    if (this.arrivalDateTextField.getText().isEmpty() == false)
    {
        try
        {
            // Check if date is correct format. Nothing will be done with 
            // the testDate object

            MyDate testDate = new MyDate(
                    this.arrivalDateTextField.getText());

            //Allow write to server to occur.
            parsedOk = true;
            //If date is okay, send form data to server.
        }
        catch (ParseException pe)
        {
            this.arrivalDateTextField.setText(""); // Set text field to blank
            int messageIcon = javax.swing.JOptionPane.ERROR_MESSAGE;
            JOptionPane.showMessageDialog(this, "Invalid date",
                    "Warning", messageIcon);
        }
    }
    else
    {
        parsedOk = true; // No date entered so allow blank. 
    }
    if (parsedOk == true)
    {
        // WRITE DATA TO SERVER OCCURS HERE: 

        try
        {

            **//getPersonDetails() returns a String[]**

            ManageClientConnections.toServer.println("addNewData");                 
       ManageClientConnections.objectToServer.writeObject(this.getPersonDetails());
            ManageClientConnections.objectToServer.flush();
            ManageClientConnections.objectToServer.reset();
        }
        catch (IOException ioe)
        {
            System.out.println(
                    "While writing new person to server, there was an error: " + ioe.getMessage());
        }

        // And dispose of the GUI, inside the parseok if clause
        this.dispose();
    }
}
4

1 回答 1

1

You can't create multiple input/output streams over the same socket input/output streams. that doesn't work. you need to pick one type of stream and stick with it. Since you need to send structured data, you should use only the Object streams and ditch the Print streams. if you need to send different types of messages from client to server, then you should consider using a wrapping Serializable object type (e.g. Message) which can contain different types of messages.

于 2013-02-19T17:00:24.060 回答