I made a simple TCP server and client in Java in different projects.When i try to send a string to my server it works,but I want to send objects to the server.I made the class for that object and made it serializable but the server and client are in different projects so how can I make the server and client to recognise the object that I am sending ?I tried to put both classes in the same project in different packages but this way I can run only the server or the client,not both.So how can I pass objects from client to server ?
3 Answers
If you use Java Serialization, you have to have the same class with the same name and ideally the same version at both ends. This is not something you can change with Java Serialization. If you want to do custom serialization you can do this, but this is not the easy way out.
I suggest you have a Jar with your data transfer objects and you share this jar with both the client and server and this will make it easier to ensure they are the same.
Comments
Split your project into three jars, client, sever and shared.
Put the transfer objects into the shared jar and deploy it on both client and server. For serialization to work you need to have the serialized classes available on both ends class pathes (and they need to be exactly identical in qualified name, that means same package and same classname).
Comments
Server and Client are two different (but similar) things. The server is there to wait for incoming requests by clients, and the clients does just that, requests things to the server.
For your Server and Client to work well there might be some conditions:
- The Server is running
- The Client knows the Server's IP and port number
See this thread for an easier and up to date solution to send objects via TCP in Java.