Chris Headleand
Chris Headleand

Reputation: 6193

Receiving serializable objects and displaying the contents

I'm writing an app in java that sends an object down a socket. At the other end of the connection I have another app that needs to receive the object and display the contents.......

I got my app to receive text by using a scanner.

in = new Scanner(socket.getInputStream());
while (in.hasNext()
{
   system.out.println(in.next)
}

However when I try to use the same method to send an object the code is incompilable. printNumber() is a meathod within the object im trying to send.

in = new Scanner(socket.getInputStream());
while (in.hasNext()
{
   system.out.println(in.printNumber())
}

I have tried looking through the internet to find a tutorial or something to explain what I'm supposed to be doing but I don't actually know what I'm actually looking for. Can anyone point me in the right direction?

Cheers

Upvotes: 0

Views: 65

Answers (2)

Mordechai
Mordechai

Reputation: 16284

First of all, you don't call a method on the sent object, but on the Scanner. No printNumber(), exists in the Scanner class.

Second, don't use a scanner for serialized objects, Scanner is designed for text input. Use ObjectInputStream instead:

in = new ObjectInputStream(socket.getInputStream()); 
System.out.println(in.readObject());

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533670

How are you Serializing the data?

If you are using ObjectOutputStream you need ObjectInputStream to read it.

If you are using XMLEncoder, you need XMLDecoder to read it.

For each serializer, there is an appropriate deserializer and you have to use the matching one.

Upvotes: 1

Related Questions