Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send object to server in java

Tags:

java

I create my class in a client and use a server for communication between client and server, but I have a problem to convert this class. I send an object of my class from the client to the server, but the server notices this object is not from the same class.

My class implements Serializable and I use ObjectInputStream and ObjectOutputStream to send and receive this object.

How can I let the server know that this object is from the same class as in the client?

//Client site.
toServer = new ObjectOutputStream(myClient.getOutputStream());
fromServer = new ObjectInputStream(myClient.getInputStream());
toServer.writeObject(new MyClass("12345",12345));


//Server site.
fromClient = new ObjectInputStream(connectFromClient.getInputStream());
toClient = new ObjectOutputStream(connectFromClient.getOutputStream());
MyClass message = (MyClass) fromClient.readObject();
like image 292
Karakob Avatar asked Mar 09 '26 04:03

Karakob


2 Answers

Create a third project, which has the classes used by both the client and the server and create a jar. Then add that jar to the classpath of the server and the client application.

like image 200
Puce Avatar answered Mar 11 '26 16:03

Puce


The classes which you serialize have to be in the same packages on the client and the server side. For example if you have serialized class Demo in package demo.bin in the client project you have to make the same serialized class in the same package in the server project. If you create the server and the client in one project please post some code to see where is the problem.

like image 25
Jordan Borisov Avatar answered Mar 11 '26 17:03

Jordan Borisov