當你想要從手機發送訊息給Arduino或想從Arduino收到回傳訊息時都必須知道如何使用DataInputStream / DataOutStream
Example01 Example02
android的網路資料交換分為2種:基於socket的,和基於http協定的。
自己玩Android 與Arduino不論是透過藍芽 HC-05、HC-06或是無線網路ESP8266 都是用Socket方式來做資料交換。網路上這篇文章說明很清楚值得大家參考
基於socket的用法
伺服器端:-----------------------------------------------------------------------------------------
先啟動一個伺服器端的socket ServerSocket svr = new ServerSocket(8989);
開始偵聽請求
Socket s = svr.accept();
取得輸入和輸出
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Socket 的交互通過流來完成,即是說傳送的位元組流,因此任何檔都可以在上面傳送。
誰打開的記得要關上。
用DataInputStream/DataOutputStream來進行包裝是因為我們想要他們對基底資料型別的讀寫功能readInt(),writeInt(),readUTF(),writeUTF()等等。
用戶端:-----------------------------------------------------------------------------------------
發起一個socket連接
Socket s = new Socket("192.168.1.16",8015);
取得輸入和輸出
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
之後就可以相互通信了。誰打開的記得要關上。
InputStream is = new FileInputStream("test");
//暫存BYTE陣列
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//緩衝
byte buffer[] = new byte[512];
//紀錄讀進來長度
int length = 0;
//假如等於-1代表沒有資料了
while( (length = is.read(buffer)) != -1){
//從緩衝區讀取buffer裡面0~length-1的位置
baos.write(buffer, 0, length);
}
//ByteArrayOutputStream轉成位元陣列
byte data [] = baos.toByteArray();
is.close();
baos.close();
基於Http協定
一般是發送請求到某個應用伺服器。此時需要用到HttpURLConnection
先取得HttpURLConnection urlConn = new URL("http://www.google.com").openConnection();
設置標誌
urlConn.setDoOutput(true); urlConn.setDoInput(true);//post的情況下需要設置DoOutput為true
urlConn.setRequestMethod("POST");
urlConn.setUseCache(false);//設置是否用緩存
urlConn.setRequestProperty("Content-type","application/x-www-form-urlencoded");//設置content-type
獲得輸出流,便於想伺服器發送資訊。
DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
望流裡面寫請求參數
dos.writeBytes("name="+URLEncoder.encode("chenmouren","gb2312");
dos.flush();dos.close();//發送完後馬上關閉。
獲得輸入流,取資料
BufferReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
reader.readLine();//用 !=null來判斷是否結束
reader.close();
讀完了記得關閉connection urlConn.disconnect();
//-----------------------------------------------
import java.io.*;
import java.net.*;
public class client
{
public static void main(String [] argv)throws IOException
{
StartClient(1234);
}
public static void StartClient(int port)
{
try
{
//設定連線的主機位置
InetAddress add = InetAddress.getByName("ecc.johnsonlu.org");
SocketAddress sc_add= new InetSocketAddress(add,port);
Socket sc = new Socket();
int timeout = 2000 ; //timeout 2秒
System.out.println("連線中....");
//與主機連線
sc.connect(sc_add,timeout);
System.out.println(sc.getLocalAddress() + "連線到" + sc.getInetAddress());
//傳送資料到Server端
DataOutputStream out = new DataOutputStream(sc.getOutputStream());
out.writeUTF("我是Client");
out.flush();
//接收Server端資料
DataInputStream in = new DataInputStream(sc.getInputStream());
System.out.println("Server:" + in.readUTF());
}
catch(SocketTimeoutException e)
{
System.out.println("Timeout");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
//----------------------------------------------
Client:
try{
Socket socket = new Socket(mDestinationIP,mDestinationPort);
DataInputStream dataInputStream = new
DataInputStream(socket.getInputStream());
int data;
//read data from server
while ((data=dataInputStream.read()) != -1) {
//do sth
}
} catch (IOException e){
//handle socket IOExceptions
}
Client Buffered data streaming
try{
Socket socket = new Socket(mDestinationIP,mDestinationPort);
BufferedInputStream bufferedInputStream = new
BufferedInputStream((socket.getInputStream());
int data;
//read date from server
while ((data= bufferedInputStream.read()) != -1) {
//do sth
}
} catch (IOException e){
//handle socket IOExceptions
}
//---------------------------------------
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.101", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}};
}