zoukankan      html  css  js  c++  java
  • 【Java__Socket 】服务端和客户端通信案例(IO流)

    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、服务端

        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();
        }
    
  • 相关阅读:
    HTML5-拖拽
    POJ1182食物链(并查集)
    欧拉函数之HDU1286找新朋友
    Another kind of Fibonacce(矩阵快速幂,HDU3306)
    我的第一道java_A+B
    bestcoder#33 1002 快速幂取余+模拟乘,组合数学
    快速幂模版
    bestcoder#33 1001 高精度模拟
    poj2446_二分图
    poj3984_bfs+回溯路径
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/13209059.html
Copyright © 2011-2022 走看看