How to get an object in java socket programming?

I am new to Java network programming.

I wrote a simple client-server code that sends a class object from the client to the server.

I used PrintStreamto send an object, and this is normal, but cannot get it on the server when usingBufferedReader

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 only accepts a string.

so my question is: "Is there a way to get a class object?"

+4
source share
1 answer
+1

Source: https://habr.com/ru/post/1620923/


All Articles