Java网络编程_传输实体类对象

来源:互联网 发布:撕衣服大战软件 编辑:程序博客网 时间:2024/06/16 19:33

实现一个登陆功能,在Socket连接以后,客户端输入账户,密码传输给服务端。现在把账户和密码作为一个用户类传输给服务端,服务端直接读取这个类。

实现过程:
首先建立一个用户类,该用户类需要序列化,序列化只需继承Serializable即可。

public class User implements Serializable{    private String account;    private String password;    public User(String account, String password){        this.account = account;        this.password = password;    }    public String getAccount() {        return account;    }    public void setAccount(String account) {        this.account = account;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    @Override    public String toString() {        return "User [account=" + account + ", password=" + password + "]";    }}

然后使用ObjectOutputStream输出,使用ObjectInputStream读入。
服务端:

public class Server {    private static final int PORT = 30000;     private ServerSocket ss = null;    private Socket s = null;    public void init() throws IOException, ClassNotFoundException{        //创建一个ServerSocket,用于监听客户端Socket的连接请求        ss = new ServerSocket(PORT);        //采用循环不断地接收客户端消息        while(true){            //接收到来自客户端发送的消息            s = ss.accept();            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());            System.out.println("客户端发送的账户密码:" + (User) ois.readObject());            //反馈客户端            PrintStream ps = new PrintStream(s.getOutputStream());            ps.print("已接受到信息~");            //关闭流            s.close();            ois.close();            ps.close();        }    }    public static void main(String[] args) throws ClassNotFoundException, IOException {        new Server().init();    }}

客户端:

public class Client {    private static final int PORT = 30000;     private Socket s = null;    public void init() throws UnknownHostException, IOException{        s = new Socket("127.0.0.1", PORT);        //发送用户信息        ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());        oos.writeObject(new User("admin", "123qwe"));        //接收服务器发来的消息        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));        String line = br.readLine();        System.out.println(line);        //关闭流        s.close();        oos.close();        br.close();    }    public static void main(String[] args) throws UnknownHostException, IOException {        new Client().init();    }}
0 0
原创粉丝点击