開心生活站

位置:首頁 > 綜合知識 > 

怎麼寫服務器端

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。

標籤:服務器端