Android客戶端與PC服務器實現Socket通信(wifi)


本文介紹Android終端持續掃描AP信息並發送給服務器端的實現。首先基於TCP協議在Android終端和PC兩端之間形成網絡虛擬鏈路。使用ServerSocket創建TCP服務器端,然后在Android客戶端使用Socket的構造器來連接服務器。其中Android終端通過WIFI連接和PC處於同一局域網。

1. PC服務器啟用ServerSocket

兩個通信實體在建立虛擬鏈路之前,需要有一方先准備好,主動接受來自其他通信實體的連接請求。

使用ServerSocket對象監聽來自客戶端的Socket連接

//創建ServerSocket對象
//by wayne from www.cnblog.com/dwayne/
ServerSocket ss = new ServerSocket(30000); //監聽來自客戶端的請求 while(true){ Socket s = ss.accept(); … }

如果沒有連接,則將一直處於等待狀態。

當接收到連接請求后,獲取消息到輸入流,並保存到文件。

//接收客戶端消息
//by wayne from www.cnblog.com/dwayne/

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String str; BufferedWriter bw = new BufferedWriter(new FileWriter("D:/ApInfo"+ (i++) +".txt")); while ((str = in.readLine()) != null) { System.out.println(str); bw.write(str); bw.newLine(); }

2. Android終端使用Socket通信

客戶端使用Socket的構造器連接服務器,指定服務器IP和端口號就可以了。

Socket s = new Socket(“192.168.1.100”, 30000);

這樣服務器端的accept()方法就得到響應,從而向下執行,服務器端和客戶端就形成了一對互相連接的Socket。再進行通信時就沒有服務器和客戶端之分了,都是通過輸入輸出流進行通信。

 詳細步驟

采用Handler和TimerTask來定時掃描AP信息並發送給服務器端。

TimerTask規定了到達指定的時間所要進行的任務。

TimerTask task = new TimerTask(){

    public void run() {
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);
    }   
       
}; 

handler傳遞message內容:

Handler handler = new Handler(){

    public void handleMessage(Message msg) {
        switch (msg.what) {
        case 1:                
            // 執行定時器時間到了之后由handler傳遞的任務
            break;
        }
        super.handleMessage(msg);
    }

};

因為需要持續執行掃描任務,所以啟用新線程執行定時任務

//啟動單獨線程定時向服務器發送AP信息
//by wayne from www.cnblogs.com/dwayne
new Thread(){ @Override public void run() { // TODO Auto-generated method stub timer.schedule(task, 2000,10000); //在2秒后每10秒執行一次定時器中的方法 } }.start();

接下來掃描AP信息並發送給服務器端,然后將結果保存。

WifiManager wifiManager=(WifiManager) getSystemService(WIFI_SERVICE);
wifiManager.startScan();
mWifiList = wifiManager.getScanResults();

由WifiManager說明可知,它可以用於處理已配置的網絡,當前連接的網絡及AP信息的掃描等情況。

This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE). It deals with several categories of items:

  • The list of configured networks. The list can be viewed and updated, and attributes of individual entries can be modified.
  • The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
  • Results of access point scans, containing enough information to make decisions about what access point to connect to.
  • It defines the names of various Intent actions that are broadcast upon any sort of change in Wi-Fi state. 

向服務器發送消息:

socket = new Socket("192.168.1.211",30000);
//向服務器端發送消息
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);        
out.println(message);

其中message為獲取的AP信息

測試收到的信息格式為:

SSID: ICIS_LAB, BSSID: 1c:af:f7:9a:65:e4, capabilities: [WPA-PSK-TKIP+CCMP], level: -80, frequency: 2437


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM