树莓派与Android客户端进行socket通信
生活随笔
收集整理的這篇文章主要介紹了
树莓派与Android客户端进行socket通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉自:https://blog.csdn.net/lj779323436/article/details/79911322
我在此基礎上時間并進行了些許修正。
先在樹莓派上創建熱點:
https://blog.csdn.net/fm0517/article/details/80939113
在樹莓派上編寫腳本代碼:tcpserver.py
#!/usr/bin/python #coding=utf-8 import socket import time import sysHOST_IP = "192.168.12.1" #我的樹莓派作為AP熱點的ip地址 HOST_PORT = 7654 #端口號print("Starting socket: TCP...") socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #創建socketprint("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) ) host_addr = (HOST_IP, HOST_PORT) socket_tcp.bind(host_addr) #綁定我的樹莓派的ip地址和端口號 socket_tcp.listen(1) #listen函數的參數是監聽客戶端的個數,這里只監聽一個,即只允許與一個客戶端創建連接while True:print ('waiting for connection...')socket_con, (client_ip, client_port) = socket_tcp.accept() #接收客戶端的請求print("Connection accepted from %s." %client_ip)socket_con.send("Welcome to RPi TCP server!") #發送數據while True:data=socket_con.recv(1024) #接收數據if data: #如果數據不為空,則打印數據,并將數據轉發給客戶端print(data)socket_con.send(data)socket_tcp.close()用AndroidStudio創建安卓工程MyApplication:
1.activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="lh.wifidemo.ui.activity.Device_Control_Activity"><TextView android:layout_width="match_parent"android:layout_height="wrap_content"android:text="設備控制"/><EditText android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/et_send"/><Button android:layout_width="match_parent"android:layout_height="wrap_content"android:text="發送"android:id="@+id/bt_send"/><TextView android:layout_width="match_parent"android:layout_height="wrap_content"android:text="接收到的信息:"/><TextView android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/tv_recv"/> </LinearLayout>2.MainActivity.java
package com.example.chenth.myapplication;import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket;/*import com.example.chenth.myapplication.R;*/public class MainActivity extends AppCompatActivity {private EditText et_send;private Button bt_send;private TextView tv_recv;private String send_buff=null;private String recv_buff=null;private Handler handler = null;Socket socket = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();handler = new Handler();//單開一個線程來進行socket通信new Thread(new Runnable() {@Overridepublic void run() {try {socket = new Socket("192.168.12.1" , 7654);if (socket!=null) {System.out.println("###################");while (true) { //循環進行收發recv();send();Thread.sleep(50);}}elseSystem.out.println("socket is null");} catch (Exception e) {e.printStackTrace();}}}).start();send();}private void recv() {//單開一個線程循環接收來自服務器端的消息InputStream inputStream = null;try {inputStream = socket.getInputStream();} catch (IOException e) {e.printStackTrace();}if (inputStream!=null){try {byte[] buffer = new byte[1024];int count = inputStream.read(buffer);//count是傳輸的字節數recv_buff = new String(buffer);//socket通信傳輸的是byte類型,需要轉為String類型System.out.println(recv_buff);} catch (IOException e) {e.printStackTrace();}}//將受到的數據顯示在TextView上if (recv_buff!=null){handler.post(runnableUi);}}//不能在子線程中刷新UI,應為textView是主線程建立的Runnable runnableUi = new Runnable() {@Overridepublic void run() {tv_recv.append("\n"+recv_buff);}};private void send() {bt_send.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {new Thread(new Runnable() {@Overridepublic void run() {send_buff = et_send.getText().toString();//向服務器端發送消息System.out.println("------------------------");OutputStream outputStream=null;try {outputStream = socket.getOutputStream();} catch (IOException e) {e.printStackTrace();}if(outputStream!=null){try {outputStream.write(send_buff.getBytes());System.out.println("1111111111111111111111");outputStream.flush();} catch (IOException e) {e.printStackTrace();}}}}).start();}});}private void initView() {et_send = (EditText) findViewById(R.id.et_send);bt_send = (Button) findViewById(R.id.bt_send);tv_recv = (TextView) findViewById(R.id.tv_recv);} }3. AndroidManifest.xml
主要是增加了網絡訪問權限:
<uses-permission android:name="android.permission.INTERNET"/> <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.chenth.myapplication"><uses-permission android:name="android.permission.INTERNET"/><application android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>這里有幾個地方需要特別注意:
1、創建socket時需要開一個子線程,而不能直接在主線程中完成,否則會報錯
2、當接收來自樹莓派服務器的消息時,需要刷新TextView,而刷新TextView的操作不能直接在子線程中完成,需要用Handler來實現,否則會報錯,提示view只能由源線程來更改
整個項目需要先啟動樹莓派,然后手機連上樹莓派的WIFI熱點,如果想要查看樹莓派的輸出信息,則可以利用window的遠程桌面連接樹莓派,也可以用putty這個軟件進行命令行控制,當然,有條件的完全可以用HDMI接口給你的樹莓派連一個顯示器
最后上圖:
圖1.樹莓派上的程序運行:
圖2.手機上的程序運行:
總結
以上是生活随笔為你收集整理的树莓派与Android客户端进行socket通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 树莓派3B创建WiFi热点
- 下一篇: 生物刺激剂技术的作用