Reputation: 93
I'm new in java network programming.
I wrote a simple client-server code that sends object of a class from client to server.
I used PrintStream
to send object and it's ok, but cannot receive it at the server when using BufferedReader
Client Code:
public class Client3 {
public String username;
public String password;
public static void main(String argv[]) throws IOException
{
Client3 account = new Client3();
account.username = "PJA";
account.password = "123456";
Socket s = new Socket("localhost",6000);
PrintStream pr = new PrintStream(s.getOutputStream());
pr.println(account);
}
}
Server Code:
public class Server3 {
public static void main(String argv[]) throws IOException
{
ServerSocket s1 = new ServerSocket(6000);
Socket s = s1.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
Client3 a = new Client3();
a = in.readLine(); // give a compilation error.
}
}
readline()
throws a compilation error because it takes only a string.
so my question is: "Is there a way to receive object of a class?"
Upvotes: 4
Views: 1068
Reputation: 121609
Q: "Is there a way to receive object of a class?"
A: Yes, there are many MANY ways:
Java RMI
Java SOAP Web services
You can use native Java serialization and write directly to a Java socket (basically, re-invent your own RMI): http://www.coderpanda.com/java-socket-programming-transferring-of-java-objects-through-sockets/, or http://www.jguru.com/faq/view.jsp?EID=10472. If you mark your objects "serializable", then you can simply useoutputStream.writeObject()
to write and ObjectInputStream()
to read.
You read and write your object state into JSON and send JSON text over your socket: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Etc. etc.
Option 3) is closest to what you're asking about. I'd also encourage you to consider Option 4). Here's a good tutorial: http://tutorials.jenkov.com/java-json/jackson-objectmapper.html
Upvotes: 1