【android 學習記錄】socket客戶端

/**
 * socket連接,客戶端
 * */

public class ClientService extends Service {

    private static final String TAG = "ClientService";

    private static ClientService instance;
    private Socket mSocket;
    private BufferedReader mInput;
    private PrintWriter mOut;
    private String content = "";
    private String mHost;


    public static ClientService getInstance () {
        if (instance == null) {
            instance = new ClientService();
        }
        return instance;
    }

    public void setIp (String ip) {
        this.mHost = ip;
    }

    @Nullable
    @Override
    public IBinder onBind (Intent intent) {
        return null;
    }

    @Override
    public void onCreate () {
        super.onCreate();
        instance = this;
    }



    /**
     * 連接調用方法
     * 傳入ip地址
     * 開始連接
     * */
    public void conn (String host) {
        if (TextUtils.isEmpty(host))
            return;
        mHost = host;
        Log.d(TAG, "開始連接");
        new Thread(connRun).start();
    }



    /**
     * 用於連接的線程
     * */
    private Runnable connRun = new Runnable() {
        @Override
        public void run () {
            Log.e(TAG, "conn:" + mHost);
            try {
                //服務器ip 端口號
                mSocket = new Socket(mHost, 8000);
                mInput = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
                mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
            } catch (IOException ex) {
                ex.printStackTrace();
                Log.e(TAG, "login exception" + ex.getMessage());
            }

            //啓動線程,接收服務器發送過來的數據
            new Thread(mHandlerMsg).start();
        }
    };


    public void sendMsg (final String msg) {
        Log.e(TAG, "給服務端發送消息 / " + (mOut == null));
        if (mOut == null || TextUtils.isEmpty(
                msg) || mSocket == null || mSocket.isClosed() || !mSocket.isConnected() || mSocket.isOutputShutdown())
        {
            Log.e(TAG,
                    "給服務端發送消息失敗:" + (mSocket == null) + " / closed:" + (mSocket.isClosed()) + " / connected:" +
                            mSocket.isConnected() + " / isoutshutdown:" + mSocket.isOutputShutdown());
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run () {
                try {
                    mOut.println(msg);
                } catch (Exception e) {
                    Log.e(TAG, "給服務端發送消息異常");
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private Runnable mHandlerMsg = new Runnable() {
        @Override
        public void run () {
            try {
                //不斷接收服務器傳來的信息
                while (true) {
                    if (!mSocket.isClosed()) {
                        if (mSocket.isConnected()) {
                            if (!mSocket.isInputShutdown()) {

                                content = "";

                                if ((content = mInput.readLine()) != null) {

                                    Log.e("ClientService", "接受信息msg:" + content);

                                    //處理信息
                                    handlerServiceMsg(content);

                                } else {

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





    /**
     * 處理接受的信息
     * */
    public void handlerServiceMsg (String msg) {
        Log.d(TAG, "處理信息:"+msg);
    }



}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章