Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EOF when serializing an object in java?

I am new in java socket programming.

My problem: I have server put in while loop to keep working.

The server has many functions to do ... one of them is adding some data.

I serialize object of a class in client then send it to the server. it done successfully but when i tried to repeat this step during the working client program i receive error java.io.EOFException

my client code:

// some data put in object named (p) of class (Product).

Socket s = new Socket("localhost",4000);
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("Add Product");
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
out.writeObject(p);
out.close();

my server code:

int i = 0;
ServerSocket s1 = new ServerSocket(4000); 
String request = null;
while(i == 0)
{
Socket ss = s1.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(ss.getInputStream()));
request = in.readLine();

switch(request){
case "Add Product":
ObjectInputStream inn = new ObjectInputStream(ss.getInputStream());
Product pr = (Product)inn.readObject();
inn.close();
e.add_product(pr);
break;

} // end of switch case.
} // end of while loop.
like image 600
PJA Avatar asked Apr 02 '26 14:04

PJA


1 Answers

You're losing data in the buffered reader. It buffers, including all or part of the following object. Get rid of the buffered reader/writer altogether. You need to use the Object streams for everything. Use writeUTF() to send the request, readUTF() to read it, and then the read/writeObject() methods you're already using.

like image 149
user207421 Avatar answered Apr 04 '26 07:04

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!