TCP通信程序练习1——服务器给出反馈,客户端接收反馈

客户端代码:

public class ClientDemo {
    public static void main(String[] args) throws IOException {
        //创建客户端Sokcet
        Socket s = new Socket("192.168.50.76", 19999);

        //调用写数据方法
        OutputStream os = s.getOutputStream();
        os.write("hello,TCP,我来了".getBytes());

        //给出反馈
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String data = new String(bys, 0, len);
        System.out.println("客户端:" + data);

        //释放资源
        s.close();
    }
}

服务器端代码:

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        //创建服务器端对象
        ServerSocket ss = new ServerSocket(19999);

        //建立连接
        Socket s = ss.accept();

        //调用读数据方法
        InputStream is = s.getInputStream();
        byte[] bys = new byte[1024];
        int len = is.read(bys);
        String data = new String(bys,0,len);
        System.out.println("服务器:"+data);

        //给出反馈
        OutputStream os = s.getOutputStream();
        os.write("数据已经收到".getBytes());

        //释放资源
        ss.close();
    }
}

服务器端运行结果:

 

 客户端运行结果:

posted @ 2020-05-09 17:04  硬盘红了  阅读(273)  评论(0编辑  收藏  举报