Android中使用BufferedReader.readline阻塞讀取不到資料,但是ready返回true

來源:互聯網
上載者:User

標籤:int   roi   class   static   取資料   buffer   his   long   blog   

通過socket測試載入器在電腦上發送訊息,Android真機可以收到響應BufferedReader.ready()返回true,但是readline卻一直阻塞。

原因:readline()只有在遇到分行符號的時候才會結束,因為發訊息的時候加一個分行符號即可。

測試載入器:http://files.cnblogs.com/files/feijian/SocketTool.rar

 

附上我的socket用戶端代碼:

public class QpushClient implements Runnable {    protected static QpushClient mInstance;    protected Handler mHandler;    protected InetSocketAddress mAddress;    protected String TAG = "QpushClient";    private final int TIME_OUT = 5 * 1000;    //巡檢周期    private final int CHECK_PERIOD = 2 * 1000;    //串連嘗試間隔時間    private final int CONNECT_PERIOD = 30 * 1000;    private final int HEARTBEART_PERIOD = 10 * 1000;    //若串連失敗或響應失敗,則嘗試次數為9,若仍無效,則不再嘗試    private final int CONNECT_TRY_TIMES = 9;    //串連嘗試次數    private int mConnectCount;    Socket mClientSocket;    String mHost;    int mPort;    //設定是否去讀取資料    boolean isStartRecieveMsg = false;    //開啟心跳檢測    boolean isKeepHeartBeat = false;    private QpushClient(Handler handler) {        mHandler = handler;    }    public static QpushClient getInstance(Handler handler) {        if (mInstance == null) {            mInstance = new QpushClient(handler);        }        return mInstance;    }    public void init(String host, int port) {        mHost = host;        mPort = port;        new Thread(this).start();        isStartRecieveMsg = true;        isKeepHeartBeat = true;    }    @Override    public void run() {        mAddress = new InetSocketAddress(mHost, mPort);        if (mClientSocket == null) {            mClientSocket = new Socket();        }        //嘗試串連,若未串連,則設定嘗試次數        while (!mClientSocket.isConnected() && mConnectCount < CONNECT_TRY_TIMES) {            connect();            if (!mClientSocket.isConnected()) {                mConnectCount++;                sleep(CONNECT_PERIOD);            } else {                mConnectCount = 0;//串連上,則恢複置0            }        }        if (mClientSocket.isConnected()) {            //開始登陸            sendMsg("login");            recvMsg();            keepHeartBeat();        }    }    private void connect() {        try {            mClientSocket.connect(mAddress);        } catch (IOException e) {            e.printStackTrace();            Log.e(TAG, "mClientSocket.connect fail " + e.getMessage());        }    }    /**     * 心跳維護     */    private void keepHeartBeat() {        //設定心跳頻率,啟動心跳        while(isKeepHeartBeat){            sendMsg("我是心跳包");            sleep(HEARTBEART_PERIOD);        }    }    BufferedWriter mWriter;    BufferedReader mReader;    /**     * 不斷的檢測是否有伺服器推送的資料過來     */    public void recvMsg() {        while (mClientSocket != null && mClientSocket.isConnected() && !mClientSocket.isClosed()) {            try {                mReader = new BufferedReader(new InputStreamReader(mClientSocket.getInputStream(), "utf-8"));                while (isStartRecieveMsg) {                    Log.e(TAG, "recvMsg5");                    if (mReader.ready()) {                        Log.e(TAG, "recvMsg6");                            /*讀取一行字串,讀取的內容來自於客戶機                            reader.readLine()方法是一個阻塞方法,                            從調用這個方法開始,該線程會一直處於阻塞狀態,                            直到接收到新的訊息,代碼才會往下走*/                        String data = mReader.readLine();                        Log.e(TAG,"isStartRecieveMsg data="+data);                        //handler發送訊息,在handleMessage()方法中接收                        handlerMsg(data);                    }                    Thread.sleep(200);                }            } catch (InterruptedException ex) {                ex.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            } catch (Exception ex) {                ex.printStackTrace();            }            sleep(200);        }        if (!mClientSocket.isConnected()) {            connect();            recvMsg();        }        sleep(CHECK_PERIOD);    }    private void sleep(long sleepTime) {        try {            Thread.sleep(sleepTime);        } catch (InterruptedException e) {            e.printStackTrace();        }    }    /**     * 銷毀socket     */    public void onDestory() {        if (mClientSocket != null) {            try {                mClientSocket.close();            } catch (IOException e) {                e.printStackTrace();            }            mClientSocket = null;        }    }    public void sendMsg(String message) {        PrintWriter writer;        try {            writer = new PrintWriter(new OutputStreamWriter(                    mClientSocket.getOutputStream()), true);            writer.println(message);        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /*     * Ready for use.     */    public void close() {        try {            if (mClientSocket != null && !mClientSocket.isClosed())                mClientSocket.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    /**     * 處理伺服器返回過來的訊息     * @param data     */    private void handlerMsg(String data){        //對資料進行protobuf解析        //訊息類型:1=登入成功、2=心跳檢測、3=推送訊息        int msgType=1;        switch(msgType){            case 1:                sendMsg("success");                break;            case 2:                sendMsg("success");                break;            case 3: //需要通知service                sendMsg("success");                mHandler.obtainMessage(QpushService.PUSH_TYPE_DATA, data).sendToTarget();                break;        }    }}

 

Android中使用BufferedReader.readline阻塞讀取不到資料,但是ready返回true

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.