之前寫過PC與android/288975.html">Android之間通過WIFI通信(通過Socket,可以在博客里面搜索),PC作為主機,Android作為客戶機,現在手頭有一臺儀器通過wifi傳輸數據,如果儀器作為主機發射WIFI熱點信號,Android需要連接到該熱點才能進一步進行通信,但是由于主機并沒有連接到網絡,所以在該種情況下Android設備無法使用網絡實現相關的網絡服務(比如關鍵數據的上傳,網絡數據的獲取等等),所以儀器在開始設計的時候將其作為客戶端,Android設備作為主機(網上的相關資料大多是將Android設備作為客戶端),當Android設備開啟熱點后,儀器會主動嘗試連接固定的熱點信息,其中網絡SSID和密碼已經寫死了,所以需要手機端手動修改熱點名稱:


在開啟熱點之后,此時手機相當于一個路由器,這個路由器的IP地址是固定的(本人測試過3臺Android設備,其默認的路由器地址:192.168.43.1,iPhone的默認路由器地址:172.20.10.1),這個Demo主要實現的目標是Android設備客戶端發送信息,服務端接受到信息后再發送信息給客戶端。那么Android設備創建的SocketServer代碼如下:
只有一個按鈕,實現在線程中啟動相對應的服務,所以在這里就不上圖了,直接放代碼:
package com.example.socketserver;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.Toast;import com.koushikdutta.async.callback.CompletedCallback;import com.koushikdutta.async.http.WebSocket;import com.koushikdutta.async.http.WebSocket.StringCallback;import com.koushikdutta.async.http.libcore.RequestHeaders;import com.koushikdutta.async.http.server.AsyncHttpServer;import com.koushikdutta.async.http.server.AsyncHttpServer.WebSocketRequestCallback;import com.koushikdutta.async.http.server.AsyncHttpServerRequest;import com.koushikdutta.async.http.server.AsyncHttpServerResponse;import com.koushikdutta.async.http.server.HttpServerRequestCallback;public class MainActivity extends Activity { private Button btnStart; private ServerSocket serverSocket; private BufferedReader in; private PrintWriter out; private Handler hander = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); String s = (String)msg.obj; Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnStart = (Button)findViewById(R.id.button1); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new ServerThread().start();//在新線程中啟動SocketServer... } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); } private class ServerThread extends Thread{ @Override public void run() { // TODO Auto-generated method stub super.run(); try {// serverSocket = new ServerSocket(50005);//默認的路由器地址為Address: 192.168.43.1 serverSocket = new ServerSocket(5000); while (true) { Socket clientSocket = serverSocket.accept();//阻塞等待處理... String remoteIP = clientSocket.getInetAddress().getHostAddress(); int remotePort = clientSocket.getLocalPort(); System.out.println("A client connected. IP:" + remoteIP+ ", Port: " + remotePort); System.out.println("server: receiving............."); // 獲得 client 端的輸入輸出流,為進行交互做準備 in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); out = new PrintWriter(clientSocket.getOutputStream(), false); // 獲得 client 端發送的數據 String tmp = in.readLine(); // String content = new String(tmp.getBytes("utf-8")); System.out.println("Client message is: " + tmp); // 向 client 端發送響應數據 out.println("Your message has been received successfully!."); // 關閉各個流 out.close(); in.close(); Message message = hander.obtainMessage(); message.obj=tmp; hander.sendMessage(message); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}客戶端實現的代碼與網上相關的資料相差無幾,比較簡單:
package com.example.serverclient;import java.io.BufferedInputStream;import java.io.IOException;import java.io.PrintStream;import java.net.Socket;import java.net.UnknownHostException;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;public class MainActivity extends Activity { private Button sendBtn,sendMessageBtn; private Socket socket; private PrintStream output; private BufferedInputStream bufferedInputStream; private ReadThread readThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendBtn = (Button) findViewById(R.id.button1); sendMessageBtn = (Button) findViewById(R.id.button2); sendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new Thread(runnable).start();//開啟線程 } }); sendMessageBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub sendMessage("hello,i am from client message"); } }); } Runnable runnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub initClientSocket(); readThread = new ReadThread(); readThread.start(); } }; public void initClientSocket() { try { socket = new Socket("192.168.43.1", 5000); output = new PrintStream(socket.getOutputStream(), true, "gbk"); } catch (UnknownHostException e) { // TODO Auto-generated catch block System.out.println("請檢查端口號是否為服務器IP"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("服務器未開啟"); e.printStackTrace(); } output.println("this is the message from client"); } public byte[] receiveData() { if (socket == null || socket.isClosed()) { try { socket = new Socket("192.168.43.1", 5000); } catch (Exception e) { e.printStackTrace(); } } byte[] data = null; if (socket.isConnected()) { try { bufferedInputStream = new BufferedInputStream(socket.getInputStream()); data = new byte[bufferedInputStream.available()]; bufferedInputStream.read(data); } catch (IOException e) { e.printStackTrace(); } } else { data = new byte[1]; } return data; } private void sendMessage(String str) { output.println(str); } public void closeSocket() { try { output.close(); socket.close(); } catch (IOException e) { System.out.println("error"+e); } } private class ReadThread extends Thread{ @Override public void run() { // TODO Auto-generated method stub super.run(); while (true) { byte[] data = receiveData(); if (data.length > 1) { System.out.println(new String(data)); } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答