package com.itant.tcpserver;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private TextView tv_from_client;
    private boolean mIsServiceDestoryed = false;
    private String ip;
    private PrintWriter out;
    private EditText et_input;
    private Button btn_send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ip = HttpTools.getLocalIpAddress();
        tv_from_client = (TextView) findViewById(R.id.tv_from_client);
        tv_from_client.setText(ip);

        et_input = (EditText) findViewById(R.id.et_input);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = et_input.getText().toString();
                if (!TextUtils.isEmpty(input)) {
                    et_input.setText("");
                    out.println(input);
                }
            }
        });

        new Thread(new TcpServer()).start();
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            tv_from_client.setText(ip + (String) msg.obj);
            return true;
        }
    });
    @Override
    public void onDestroy() {
        super.onDestroy();
        mIsServiceDestoryed = true;
    }

    private class TcpServer implements Runnable {

        @SuppressWarnings("resource")
        @Override
        public void run() {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(8688);
            } catch (IOException e) {
                System.err.println("establish tcp server failed, port:8688");
                e.printStackTrace();
                return;
            }

            while (!mIsServiceDestoryed) {
                try {
                    // 接受客户端请求
                    final Socket client = serverSocket.accept();
                    System.out.println("accept");
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                responseClient(client);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        };
                    }.start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void responseClient(Socket client) throws IOException {
        // 用于接收客户端消息（先获取读的流）
        BufferedReader in = new BufferedReader(
                new InputStreamReader(client.getInputStream()));

        // （才能获取写的流）
        // 用于向客户端发送消息(有成员变量指向这里，所以会阻塞accept方法，一次只能应对一个客户端)
        out = new PrintWriter(
                new BufferedWriter(
                        new OutputStreamWriter(client.getOutputStream())), true);
        out.println("欢迎来到聊天室！");

        // 再循环地去读
        while (!mIsServiceDestoryed) {
            String str = in.readLine();
            System.out.println("msg from client:" + str);
            if (str == null) {
                break;
            }
            Message message = Message.obtain();
            message.obj = str;
            message.what = 0;
            mHandler.sendMessage(message);

        }

        System.out.println("client quit.");
        // 关闭流
        out.close();
        in.close();
        client.close();
    }

}
