0

Can someone please resolve this issue. Using JDK 1.8, I am trying to build a very simple chat application in Java using Sockets. In my client class as soon as following line executes Message returnMessage = (Message) objectInputStream.readObject(); it throws exception. Exception in thread "main" java.io.OptionalDataException

I am writing only objects of type Message to the stream and reading objects of type Message, since i wrote once, i dont think i am doing anything wrong in reading them in sequence.

Q. Also please let me know what is the best way to debug this type of application, how to hit the breakpoint in server while running client ?

Client

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;
    }
}

Server

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();
        }
    }
}

Sever Thread

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());
    }
}

Message Class

 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 +
                '}';
    }
}
5
  • Please help yourself to some complementary debugging techniques. If you still have issues afterwards, please feel free to come back with a Minimal, Complete and Verifiable Example that demonstrates your problem. Commented Apr 13, 2017 at 5:38
  • I know how to do debugging in java, i can debug client, but my breakpoint in server is not hitting, i think there is a different technique to debug these type of client server applications. Commented Apr 13, 2017 at 5:46
  • In that case, my suggestion is to double-check you are running in debug mode, and then move your breakpoint somewhere it is more likely to be hit. Commented Apr 13, 2017 at 5:47
  • @ATHER You have added the code of Serversocket in Message class.Please update and add the correct Message class. Commented Apr 13, 2017 at 6:36
  • @Pallavi Thanks for mentioning that, i will do that once i get back to my computer. Sorry about that. Commented Apr 13, 2017 at 13:55

1 Answer 1

2
 objectOutputStream.writeChars("\n");

Why are you writing a newline to an ObjectOutputStream? You're never reading it. Don't do that. Remove this wherever encountered.

Sign up to request clarification or add additional context in comments.

4 Comments

I had to do that because my input stream was blocked on the client side. I will try to remove it and will update you anyways. Let's see if that works.
No, you didn't 'have to do that because the input stream was blocked on the client side'. The flush() was all you needed.
I still don't quite understand, why adding a new line was preventing form the client side when i was doing objectInputStream.readObject( );
I stilll don't understand why you thought it would accomplish anything useful. It mystifies me why you thought it would solve anything, and why you thought it would not cause a problem. You can't just write arbitrary data down a connection that the other side isn't reading and expect it to magically understand the data stream. It doesn't begin to make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.