當前位置:生活全書館 >

綜合知識

> 伺服器端怎麼寫

伺服器端怎麼寫

1. socket通訊伺服器端怎麼寫

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 /dwayne/ServerSocket ss = new ServerSocket(30000);//監聽來自客戶端的請求while(true){Socket s = ss.accept();…}如果沒有連線,則將一直處於等待狀態。當接收到連線請求後,獲取訊息到輸入流,並儲存到檔案

//接收客戶端訊息//by wayne from /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 /dwaynenew Thread(){@Overridepublic void run() {// TODO Auto-generated method stubtimer.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: 2。

標籤: 伺服器端
  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zonghezhishi/4yw443.html