package com.njh.socket.TCPSocketHalfDuplexContact;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 *ClassName: SocketClient
 *Description: 半双工通信客户端
 *Author: njh
 *Time: ,14:47
 *Version: V1.0
 *
 **/
public class SocketClient{
    private Socket socket;//使用TCP协议
    //private DatagramSocket datagramSocket;  //可以用UDP协议

    public SocketClient(String ip, int port){
        try{
            socket = new Socket(ip,port);
            start();
        }
        catch(Exception e){
            e.printStackTrace();
        }

    }

    public void start() throws Exception{
        //获取socket传过来的字节流转成缓冲流，以提高性能
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        //将字节流转成字符流
        InputStreamReader isr = new InputStreamReader(bis);
        //OutputStreamWriter osw = new OutputStreamWriter(bos);
        PrintWriter pw = new PrintWriter(bos);
        //获取服务器传来的信息
        BufferedReader br = new BufferedReader(isr);
        //结束语为over
        String info = "";
        while(!info.equals("over")){//规定：服务器先发送信息，读写顺序不能乱不然会阻塞
            //先读取信息
            info = br.readLine();//查看源码发现BufferReader的readLine()加锁后对\n跳过，所以之前加\n或者\r已经不再适用。除非提前在append \n或\r时加锁
                                 //I/O阻塞也可以通过多线程来规避
            if(!info.equals("")&&info.length()!=0)
                System.out.println("Server send message : " + info);
            //再写信息
            Scanner sc = new Scanner(System.in);
            info = sc.nextLine();

            System.out.println("Send to Server ： " + info);
            //osw.write(info);
            //osw.flush();
            pw.println(info);//为什么选择PrintWriter而不是OutputStreamWriter？
            pw.flush();      //是因为BufferReader.readLine()是阻塞的，除非遇到换行或者回车符号，不然不会继续执行
                             //查看PrintWriter.println()源码后发现在print(info)后又调用了println()。正好构成了换行
        }
        //关闭读取流
        br.close();
        //关闭字符流
        //osw.close();
        isr.close();
        pw.close();
        //关闭缓冲流
        bos.close();
        bis.close();
        //关闭socket连接
        socket.close();
    }

    public static void main(String[] args){
        new SocketClient("127.0.0.1",6666);
    }

}
