java客户端服务器端的对象传输

//实体类
public class User implements Serializable{

private String name;
private String password;

public User(String name, String password) {
    super();
    this.name = name;
    this.password = password;
}

@Override
public String toString() {
    return "User [name=" + name + ", password=" + password + "]";
}

//服务器端
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {

        ServerSocket ss = new ServerSocket(10010);

        Socket s = ss.accept();

        InputStream in = s.getInputStream();

        ObjectInputStream ois = new ObjectInputStream(in);

        Object obj = ois.readObject();

        System.out.println(obj);

        ois.close();
        in.close();
        ss.close();

    }

}

//客户端
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {

    Socket s = new Socket("127.0.0.1",10010);

    OutputStream out = s.getOutputStream();

    ObjectOutputStream oos = new ObjectOutputStream(out);

    User user = new User("张三","111");

    oos.writeObject(user);

    oos.close();
    out.close();
    s.close();
}

}

猜你喜欢

转载自blog.csdn.net/weixin_42337796/article/details/81909757
今日推荐