zoukankan      html  css  js  c++  java
  • 流式套接字:基于TCP协议的Socket网络编程(案例3)

    案例:在案例1的基础上将传输的字符串换成具体的对象。

    客户端代码:

    package com.yh.SocketObject;
    
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class LoginClient {
        public static void main(String[] args) {
            Student stu = new Student("YeHuan",23);
            try {
                Socket socket = new Socket("localhost",5001);
                OutputStream os = socket.getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);
                oos.writeObject(stu);
                socket.close();
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    服务器代码:

    package com.yh.SocketObject;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectInputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class LoginServer {
        public static void main(String[] args) {
            try {
                ServerSocket sc = new ServerSocket(5001);
                Socket socket = sc.accept();
                InputStream is = socket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(is);
                Student stu = (Student) ois.readObject();
                System.out.println(stu.name +" " + stu.age + "岁");
                sc.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Student类:

    package com.yh.SocketObject;
    
    import java.io.Serializable;
    
    public class Student implements Serializable {
        private static final long serialVersionUID = 1L;
        public int age;
        public String name;
        
        public Student() {}
        public Student(String name,int age) {
            this.name = name;
            this.age = age;
        }
    }
  • 相关阅读:
    bzoj1083: [SCOI2005]繁忙的都市 瓶颈生成树
    Codeforces Round #344 (Div. 2)C. Report
    Wannafly挑战赛14E无效位置
    Codeforces Round #378 (Div. 2)F
    1059: [ZJOI2007]矩阵游戏 二分图匹配
    Educational Codeforces Round 42 (Rated for Div. 2)F
    bzo1016: [JSOI2008]最小生成树计数
    bzoj1009: [HNOI2008]GT考试 ac自动机+矩阵快速幂
    bzoj1070: [SCOI2007]修车
    table表格frame属性
  • 原文地址:https://www.cnblogs.com/YeHuan/p/10792902.html
Copyright © 2011-2022 走看看