socket使用相關

來源:互聯網
上載者:User
在一個練習小項目中學習到的




  1. package com.sdut.edu.tools;
  2. import java.io.BufferedWriter;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStreamWriter;
  6. import java.io.PrintWriter;
  7. import java.net.InetSocketAddress;
  8. import java.net.Socket;
  9. import java.net.SocketAddress;
  10. import java.net.SocketException;
  11. import java.util.Scanner;
  12. import android.app.ActivityManager;
  13. import android.app.AlertDialog;
  14. import android.content.Context;
  15. import android.content.DialogInterface;
  16. import android.util.Log;
  17. public class ConnectServer {
  18. public String connectServer(String str) throws SocketException,IOException
  19. {//獲得從伺服器的響應字串
  20. // TODO Auto-generated method stub
  21. String result = null;
  22. StringBuffer tempStr=new StringBuffer();//最終返回的結果
  23. // try{
  24. int c=0;
  25. //根據伺服器的IP和連接埠號碼建立一個socket對象,建立與伺服器的串連
  26. Socket socket=new Socket();
  27. //Socket的構造方法,
  28. socket.connect(new InetSocketAddress("192.168.0.189",4444),4000);
  29. //接收從伺服器獲得的資料額對象
  30. // if(socket.getRemoteSocketAddress()==null)
  31. // {
  32. //
  33. // }
  34. //socket.connect(remoteAddr);
  35. //BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"),10000);
  36. InputStream is=socket.getInputStream(); //接收資料的轉碼問題
  37. Scanner in=new Scanner(is);
  38. //根據已經建立的socket建立PrintWriter對象,並通過這個對象將資訊發送給伺服器。
  39. PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8")),true);
  40. //訊息發送
  41. out.println(str);
  42. Log.d("ListAdapter_getvediourl_isConnected",socket.isConnected()+"");
  43. //判斷連線逾時
  44. if(socket.isConnected())//判斷用戶端與伺服器端的串連,接收響應的字串
  45. {
  46. while(in.hasNextLine())
  47. {
  48. result=in.nextLine();
  49. tempStr.append(result);
  50. System.out.println(tempStr);
  51. }
  52. }
  53. else
  54. {
  55. System.out.println("串連服務逾時");
  56. }
  57. out.close();
  58. in.close();
  59. socket.close();//完成後。關閉socket
  60. // }catch(SocketException e)
  61. // {
  62. // return "-1";
  63. // //System.out.println("串連失敗");
  64. // //e.printStackTrace();
  65. // }catch(IOException e){
  66. // return "-2";
  67. // }
  68. return tempStr.toString();
  69. }
  70. }
複製代碼
  • 聯繫我們

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