简体   繁体   中英

How to receive object in java socket programming?

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?"

Q: "Is there a way to receive object of a class?"

A: Yes, there are many MANY ways:

  1. Java RMI

  2. Java SOAP Web services

  3. 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 use outputStream.writeObject() to write and ObjectInputStream() to read.

  4. 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/

  5. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM