package com.koobietech.eas.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * ClassName: ChatClient
 * Package: com.lc.chat
 * Description:
 *
 * @Author 爱扣钉-陈晨
 * @Create 2023/8/18 9:00
 * @Version 1.0
 */
public class ChatClient {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        //请输入链接地址
        //创建网络链接对象Socket
        Socket socket = new Socket("192.168.18.32",9999);
        System.out.println("链接系统成功,请输入个人昵称,bye退出");
        String nickname = scanner.nextLine();
        //发送线程
        SendThread send = new SendThread(socket,nickname);
        send.start();

        //接收线程
        ReceiveThread receive = new ReceiveThread(socket);
        receive.start();
        //插队
        send.join();

    }
}
class ReceiveThread extends Thread{
    Socket socket;

    public ReceiveThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //获取输入字节流
            InputStream is = socket.getInputStream();
            Scanner scanner = new Scanner(is);
            //循环
            while (scanner.hasNextLine()){
                String s1 = socket.getInetAddress().toString().substring(1);
                String s2 = InetAddress.getLocalHost().getHostAddress();
                if (!s1.equals(s2)){
                    String s = scanner.nextLine();
                    System.out.println(s);
                }

            }
            socket.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
class SendThread extends Thread {
    private Socket socket;

    private String nickname;

    public SendThread(Socket socket , String nickname ) throws IOException {
        this.socket = socket;
        this.nickname = nickname;

        //获取输出字节流
        OutputStream os = socket.getOutputStream();
        PrintStream ps = new PrintStream(os);
        //发送名称
        ps.println( nickname);
    }

    @Override
    public void run() {
        try {
            //获取输出字节流
            OutputStream os = socket.getOutputStream();
            PrintStream ps = new PrintStream(os);
            //键盘输入
            Scanner scanner = new Scanner(System.in);
            //循环
            while (true){

                String str = scanner.nextLine();
                if (str.equals("bye")){
                    break;
                }
                ps.println( nickname+"："+ str);

            }
            socket.shutdownOutput();
            socket.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

