首页 > 其他 > 详细

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

时间:2020-05-09 17:36:24      阅读:63      评论:0      收藏:0      [点我收藏+]

技术分享图片

客户端代码:

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();
    }
}

服务器端运行结果:

技术分享图片

 

 客户端运行结果:

技术分享图片

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

原文:https://www.cnblogs.com/pxy-1999/p/12858810.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!