安卓面試技術點之xmpp知識準備Socket伺服器的終結,安卓xmpp

來源:互聯網
上載者:User

安卓面試技術點之xmpp知識準備Socket伺服器的終結,安卓xmpp

上一節基本是已經完成了,伺服器端和用戶端的通訊,但是並沒有實現長串連通訊,這一節將bug修複


1.用戶端代碼編寫 我們需要開啟一個線程去進行等待伺服器發送訊息過來
public void startServerReplyListener(final BufferedReader serverToClientMsg){new Thread(new Runnable() {@Overridepublic void run() {try {String responce;while ((responce=serverToClientMsg.readLine())!=null) {System.out.println(responce);}} catch (IOException e) {e.printStackTrace();}}}).start();}


2.伺服器端代碼編寫  其實對於所有伺服器端來說,不可能服務一個用戶端,然後我們以前代碼只要用戶端一串連,就不會再去讓用戶端串連了,所以代碼要改一下, 用while迴圈 一起去迴圈,等待用戶端串連 
//進入阻塞狀態,等待用戶端介入 ,返回一個socket對象while (true) {client = socket.accept();ManagerConnection(client);}

然後開啟線程 回複資訊
public void ManagerConnection(final Socket socket){new Thread(new Runnable() {@Overridepublic void run() {try {System.out.println("用戶端"+socket.hashCode()+"串連上");clientToServerMsg = new BufferedReader(new InputStreamReader(client.getInputStream()));serverToClientMsg = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));String readermsg;//一行一行讀取賦值while ((readermsg=clientToServerMsg.readLine())!=null) {System.out.println(readermsg);System.out.println("用戶端"+socket.hashCode()+":"+readermsg);serverToClientMsg.write("伺服器回複"+readermsg+"\n");serverToClientMsg.flush();  }} catch (IOException e) {e.printStackTrace();}finally{try {clientToServerMsg.close();serverToClientMsg.close();} catch (IOException e) {e.printStackTrace();}}}}).start();}
End
未完待續
點擊下載源碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.