objectInputStream.readObject()抛出异常java.io.OptionalDataException

时间:2017-04-13 05:37:19

标签: java serversocket

有人可以解决此问题。 使用JDK 1.8,我试图使用套接字在Java中构建一个非常简单的聊天应用程序。在我的客户端类中,只要执行以下行  消息returnMessage =(Message)objectInputStream.readObject(); 它抛出异常。 线程“main”中的异常java.io.OptionalDataException

我只在流中写入Message类型的对象并读取Message类型的对象,因为我写了一次,我不认为我在按顺序读取它们时做错了什么。

Q值。另请告诉我调试此类应用程序的最佳方法是什么,如何在运行客户端时点击服务器中的断点?

客户端

package com.company;

import sun.misc.SharedSecrets;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException{

            Socket socket = new Socket("localhost", Server.PORT);

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String readerInput = bufferedReader.readLine();
            String[] readerInputTokens = readerInput.split("\u0020");

            if(readerInputTokens.length != 2) {
                System.out.println("Usage: Client <integer> <integer>");
            } else {
                Integer firstNumber = Integer.decode(readerInputTokens[0]);
                Integer secondNumber = Integer.decode(readerInputTokens[1]);

                Message message = new Message(firstNumber, secondNumber);

                objectOutputStream.writeObject(message);


                System.out.println("Reading Object .... ");
                Message returnMessage = (Message) objectInputStream.readObject();

                System.out.println(returnMessage.getResult());

                socket.close();
            }
    }

    public static boolean isInteger(String value) {
        boolean returnValue = true;
        try{Integer.parseInt(value);}
        catch (Exception ex){ returnValue = false; }
        return returnValue;
    }
}

服务器

package com.company;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
    public final static int PORT = 4446;
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        new Server().runServer();
    }

    public void runServer() throws IOException, ClassNotFoundException {

        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("Server up & ready for connections ...");

        // This while loop is necessary to make this server able to continuously in listning mode
        // So that whenever a client tries to connect, it let it connect.
        while (true){
            Socket socket = serverSocket.accept(); // Server is ready to accept connectiosn;.

            // Initialize Server Thread.
            new ServerThread(socket).start();
        }
    }
}

服务器主题

package com.company;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ServerThread extends Thread {
    private Socket socket = null;
    ServerThread(Socket socket){
        this.socket = socket;
    }

    public void run() {

        try {

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeChars("\n");
            objectOutputStream.flush();

            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

            Message message = (Message) objectInputStream.readObject();
            multiplyNumbers(message);
            System.out.println("Writing: "+message.toString());
            objectOutputStream.writeObject(message);
            System.out.println("Message Written");
            socket.close();

        } catch( IOException ex) {
            ex.printStackTrace();

        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    private void multiplyNumbers(Message message) {
        message.setResult(message.getFirstNumber().intValue() * message.getSecondNumber().intValue());
    }
}

邮件类

 package com.company;

import java.io.Serializable;

public class Message implements Serializable {
    private static final long serialVersionUID = -72233630512719664L;

    Integer firstNumber = null;
    Integer secondNumber = null;
    Integer result = null;

    public Message(Integer firstNumber, Integer secondNumber) {
        this.firstNumber = firstNumber;
        this.secondNumber = secondNumber;
    }

    public Integer getFirstNumber() {
        return this.firstNumber;
    }

    public Integer getSecondNumber() {
        return this.secondNumber;
    }

    public Integer getResult() {
        return this.result;
    }

    public void setResult(Integer result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return "Message{" +
                "firstNumber=" + firstNumber +
                ", secondNumber=" + secondNumber +
                ", result=" + result +
                '}';
    }
}

1 个答案:

答案 0 :(得分:2)

 objectOutputStream.writeChars("\n");

为什么要为ObjectOutputStream写一个换行符?你永远不会读它。不要那样做。无论遇到什么地方都要删除它。