package com.huimv.datacollection.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <p>
 *
 * </p>
 *
 * @author yinhao
 * @date 2021/7/7 9:55
 */
public class TcpSendAndRecv {


    public static void main(String[] args) {
        //先开启接收端的线程
        new Thread(new DD()).start();
        //在开启发送端的线程
        new Thread(new TT()).start();


    }
}

class TT implements Runnable {

    @Override
    public void run() {
        try {
            //创建一个socket绑定的端口和地址为：9977，本机。
            Socket s = new Socket("localhost", 9977);
            //获取到输出流
            OutputStream oos = s.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(oos));
            System.out.print("发送端:");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.flush();
                //将内容写到控制台
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}

class DD implements Runnable {

    @Override
    public void run() {
        try {
            //创建一个serversocket其端口与发送端的端口是一样的
            ServerSocket ss = new ServerSocket(9977);
            //侦听并接受到此套接字的连接，返回一个socket对象
            Socket s = ss.accept();
            //获取到输入流
            InputStream is = s.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            //接收收到的数据
            byte[] buf = new byte[1024];
            int line = 0;
            while ((line = is.read(buf)) != -1) {
                //将接收到的数据在控制台输出
                System.out.println("接收端" + new String(buf, 0, line));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}
