Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

android 客戶端基於套接字訪問網絡調試助手實現一問一答工具類

編輯:關於 Android 程式設計

下面這個工具方法封裝了通過 Socket 連接服務器、發送消息並接收返回數據的完整流程,可用於與網絡調試助手進行一問一答式的通信:

/** * 連接服務器 * @param serverIp 服務器ip * @param port 端口 * @param msg 消息 * @return 服務端返回數據 */ public static String getSocketResult(String serverIp,int port,String msg){ Socket socket=null; String result=null; InputStream in=null; OutputStream outputStream=null; try { //套接字連接服務器 InetAddress severAddress=InetAddress.getByName(serverIp); socket=new Socket(severAddress, port); outputStream=socket.getOutputStream(); outputStream.write(msg.getBytes("gbk")); outputStream.flush(); in=socket.getInputStream(); int count=0; byte[] inDatas = null; while (count == 0) { count = in.available(); } inDatas = new byte[count]; in.read(inDatas); in.close(); return new String(inDatas, "gb2312"); } catch (Exception e) { // TODO: handle exception }finally{ if(outputStream!=null){ try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(in!=null){ try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(socket!=null){ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return result; }

該方法先通過 InetAddress 解析服務器地址並建立 Socket 連接,以 gbk 編碼發送消息,再循環等待並讀取返回數據,最後以 gb2312 解碼返回;同時在 finally 塊中對輸出流、輸入流與 Socket 進行了完整的資源釋放,避免連接洩漏。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved