Android設(shè)備之間通過Wifi通信的示例代碼
之前寫過PC與Android之間通過WIFI通信(通過Socket,可以在博客里面搜索),PC作為主機(jī),Android作為客戶機(jī),現(xiàn)在手頭有一臺儀器通過wifi傳輸數(shù)據(jù),如果儀器作為主機(jī)發(fā)射WIFI熱點(diǎn)信號,Android需要連接到該熱點(diǎn)才能進(jìn)一步進(jìn)行通信,但是由于主機(jī)并沒有連接到網(wǎng)絡(luò),所以在該種情況下Android設(shè)備無法使用網(wǎng)絡(luò)實(shí)現(xiàn)相關(guān)的網(wǎng)絡(luò)服務(wù)(比如關(guān)鍵數(shù)據(jù)的上傳,網(wǎng)絡(luò)數(shù)據(jù)的獲取等等),所以儀器在開始設(shè)計的時候?qū)⑵渥鳛榭蛻舳耍珹ndroid設(shè)備作為主機(jī)(網(wǎng)上的相關(guān)資料大多是將Android設(shè)備作為客戶端),當(dāng)Android設(shè)備開啟熱點(diǎn)后,儀器會主動嘗試連接固定的熱點(diǎn)信息,其中網(wǎng)絡(luò)SSID和密碼已經(jīng)寫死了,所以需要手機(jī)端手動修改熱點(diǎn)名稱:


在開啟熱點(diǎn)之后,此時手機(jī)相當(dāng)于一個路由器,這個路由器的IP地址是固定的(本人測試過3臺Android設(shè)備,其默認(rèn)的路由器地址:192.168.43.1,iPhone的默認(rèn)路由器地址:172.20.10.1),這個Demo主要實(shí)現(xiàn)的目標(biāo)是Android設(shè)備客戶端發(fā)送信息,服務(wù)端接受到信息后再發(fā)送信息給客戶端。那么Android設(shè)備創(chuàng)建的SocketServer代碼如下:
只有一個按鈕,實(shí)現(xiàn)在線程中啟動相對應(yīng)的服務(wù),所以在這里就不上圖了,直接放代碼:
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);//默認(rèn)的路由器地址為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 端的輸入輸出流,為進(jìn)行交互做準(zhǔn)備
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), false);
// 獲得 client 端發(fā)送的數(shù)據(jù)
String tmp = in.readLine();
// String content = new String(tmp.getBytes("utf-8"));
System.out.println("Client message is: " + tmp);
// 向 client 端發(fā)送響應(yīng)數(shù)據(jù)
out.println("Your message has been received successfully!.");
// 關(guān)閉各個流
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();
}
}
}
}
客戶端實(shí)現(xiàn)的代碼與網(wǎng)上相關(guān)的資料相差無幾,比較簡單:
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("請檢查端口號是否為服務(wù)器IP");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("服務(wù)器未開啟");
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);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android 實(shí)現(xiàn)無網(wǎng)絡(luò)頁面切換的示例代碼
本篇文章主要介紹了Android 實(shí)現(xiàn)無網(wǎng)絡(luò)頁面切換的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
關(guān)于Android Activity之間傳遞數(shù)據(jù)的6種方式
這篇文章主要介紹了關(guān)于Android Activity之間傳遞數(shù)據(jù)的6種方式,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03
Android中如何指定SnackBar在屏幕的位置及小問題解決
這篇文章主要給大家介紹了關(guān)于Android中如何指定SnackBar在屏幕的位置,以及一個小問題解決的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03
Android編程學(xué)習(xí)之異步加載圖片的方法
這篇文章主要介紹了Android編程學(xué)習(xí)之異步加載圖片的方法,以實(shí)例形式較為詳細(xì)的分析了Android異步加載圖片所涉及的頁面布局及功能實(shí)現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10

