分享

【Java

 昵称70680357 2020-06-29

0、前言

Java IO 流分为输入流InputStream和输出流OutputStream

输入流 输出流
InputStream OutputStream
读进来 写出去
读到程序内存 写出到流里面

1、客户端

    public static void main(String[] args) throws IOException {
        new Thread(() -> {
            Socket socket = null;
            try {
                socket = new Socket("", 3333);
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                while (true) {
                    OutputStream outputStream = socket.getOutputStream();
                    String format = DateFormat.getDateTimeInstance().format(new Date());
                    outputStream.write((format + " hello world!").getBytes());
                    Thread.sleep(2000);
                }
            } catch (Exception e) {

            }
        }).start();
    }

2、服务端

语言 方法
4729 nL904Tx9U1
78UD9 上班族副业
5774 2009.08.24 19-46-32
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(3333);
        new Thread(() -> {
            while (true) {
                try {
                    Socket accept = serverSocket.accept();
                    new Thread(() -> {
                        try {
                            int len;
                            byte[] data = new byte[1024];
                            InputStream inputStream = accept.getInputStream();
                            while ((len = inputStream.read(data)) != -1) {
                                System.out.println(new String(data, 0, len));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }).start();
                } catch (Exception e) {

                }
            }
        }).start();
    }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多