安卓app和云端交互

APP和云端交互

1.云端服务期器编程
2.APP编程
在这里插入图片描述

云端TCP编程

import socket
HOST = ''  # 监听所有可用的网络接口
PORT = 65433  # 使用一个未被占用的端口号
last_response = ""


def send_data(conn, data):
    """发送数据并处理异常"""
    try:
        conn.sendall(data.encode())
        print("消息发送成功")
    except Exception as e:
        print(f"发送失败: {e}")
        return False
    return True


def read_last_n_lines(file_path, n=10):
    """读取文件的最后n行"""
    try:
        with open(file_path, 'rb') as file:
            lines = []
            buffer = bytearray()
            while True:
                chunk = file.read(1024)
                if not chunk:
                    break
                buffer.extend(chunk)
                while b'\n' in buffer:
                    pos = buffer.find(b'\n')
                    line = buffer[:pos + 1]
                    buffer = buffer[pos + 1:]
                    lines.append(line.decode().strip())
            return lines[-n:]
    except Exception as e:
        print(f"读取文件失败: {e}")
        return []


def read_last_line(file_path):
    """读取文件的最后一行"""
    try:
        with open(file_path, 'rb') as file:
            file.seek(-2, 2)  # 移动到文件末尾前一个字符
            while file.read(1) != b'\n':  # 寻找最后一个换行符
                file.seek(-2, 1)
            last_line = file.readline().decode()
            return last_line.strip()
    except Exception as e:
        print(f"读取文件失败: {e}")
        return ""


def handle_client(conn, addr, file_path):
    """处理客户端连接"""
    print(f"已连接到: {addr}")

    # 读取文件的最后10行
    last_10_lines = read_last_n_lines(file_path, 10)
    for line in last_10_lines:
        response = f"{line}\n"
        if not send_data(conn, response):
            break

    while True:
        try:
            print("开始接收")
            data = conn.recv(1024)
            print("接收完成")
        except socket.timeout:
            print("接收超时")
            break
        except Exception as e:
            print(f"接收失败: {e}")
            break

        if not data:
            break

        print(f"接收到: {data.decode()}")

        # 读取文件的最后一行
        last_line = read_last_line(file_path)

        # 向客户端发送响应消息
        response = f"{last_line}\n"
        if response != last_response:
            if send_data(conn, response):
                last_response = response
            else:
                break

    print("连接关闭")


def main():
    # 创建一个 socket 对象
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.settimeout(5)

    # 设置 SO_REUSEADDR 选项 以允许重用地址和端口
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 绑定 socket 对象到指定的地址和端口
    server_socket.bind((HOST, PORT))

    # 开始监听连接
    server_socket.listen()

    print("等待连接...")

    while True:
        try:
            conn, addr = server_socket.accept()
            conn.settimeout(5)
            file_path = "/home/Testpy/P2PLOG_RLM.csv"
            handle_client(conn, addr, file_path)
        except socket.timeout as e:
            print("连接超时")
            continue
        except Exception as e:
            print(f"处理连接时发生错误: {e}")


if __name__ == "__main__":
    main()

说明:
初始化变量:

last_response 用于记录上次发送的响应。
函数定义:

send_data(conn, data):发送数据并处理异常。
read_last_n_lines(file_path, n=10):读取文件的最后n行。
read_last_line(file_path):读取文件的最后一行。
handle_client(conn, addr, file_path):处理客户端连接,发送文件的最后10行,后续每次发送一行。
主函数 main():

创建服务器套接字并设置超时时间。
绑定地址和端口并开始监听连接。
循环接受客户端连接,并调用 handle_client 处理每个连接。
处理客户端连接:

首次连接时发送文件的最后10行。
每次接收到客户端的数据后,读取文件的最后一行,并发送给客户端。
使用 last_response 变量确保只有当最后一行发生变化时才发送新的响应。
这样可以确保首次连接时发送文件的最后10行,后续每次发送一行,并且在发送过程中进行适当的错误处理。
其中:
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
允许重用端口,因为经常因为端口断开不够彻底导致端口未释放,导致无法使用该端口。

APP编程

添加一个EditText , 在一个页面中添加一个多行文本框,并设置其不可编辑。

<EditText
    android:id="@+id/editTextTextMultiLine"
    android:layout_width="398dp"
    android:layout_height="674dp"
    android:layout_marginTop="16dp"
    android:layout_marginBottom="24dp"
    android:ems="10"
    android:gravity="start|top"
    android:inputType="textMultiLine"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    tools:layout_editor_absoluteX="10dp"
    android:editable="false"/>

本案例在…/…/…/…/…/AndroidStudioProjects/MyApplication3/app/src/main/res/layout/fragment_first.xml
中添加了一个文本框

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <fragment
        android:id="@+id/nav_host_fragment_content_main"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav_graph" />

    <EditText
        android:id="@+id/editTextTextMultiLine"
        android:layout_width="398dp"
        android:layout_height="674dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="24dp"
        android:ems="10"
        android:gravity="start|top"
        android:inputType="textMultiLine"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:layout_editor_absoluteX="10dp"
        android:editable="false"/>


</androidx.constraintlayout.widget.ConstraintLayout>

获取网络权限

…/…/…/…/…/AndroidStudioProjects/MyApplication3/app/src/main/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"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:theme="@style/Theme.MyApplication">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

代码实现

…/…/…/…/…/AndroidStudioProjects/MyApplication3/app/src/main/java/com/example/myapplication/MainActivity.kt
这段代码实现了一个 Android 应用程序,其中包含了与服务器进行 TCP 通信的功能。以下是代码的主要功能和结构:

主要功能
初始化 UI 和导航组件
设置定时任务来发送数据到服务器
发送数据并接收响应

package com.example.myapplication

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import java.io.OutputStream
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import com.example.myapplication.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import java.net.InetAddress
import java.net.Socket
import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader
import android.widget.TextView
import android.widget.EditText
import android.text.method.ScrollingMovementMethod

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding

    //新增代码:
    private lateinit var handler: Handler
    private lateinit var socketTask: Runnable
    private var socket: Socket? = null
    private  val SERVER_IP : String = "115.29.204.91" // 替换为你的 IP 地址
    private  val SERVER_PORT: Int = 65433 // 替换为你的端口
    private  val INTERVAL_MS: Long = 1000 // 1秒
    private  var message1: Long = 1 // 1秒

    private lateinit var messageEditText: EditText


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //新增代码:
        handler = Handler(Looper.getMainLooper())
            socketTask = object : Runnable {
                override fun run() {
                    sendSocketData()
                    handler.postDelayed(this, INTERVAL_MS)
                }
            }
        handler.post(socketTask);


        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)

        val navController = findNavController(R.id.nav_host_fragment_content_main)
        appBarConfiguration = AppBarConfiguration(navController.graph)
        setupActionBarWithNavController(navController, appBarConfiguration)

        binding.fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null)
                .setAnchorView(R.id.fab).show()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // 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.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration)
                || super.onSupportNavigateUp()
    }
    private fun sendSocketData() {
        Thread {
            try {
                val mysocket = getSocket()
                if (mysocket != null) {
                    println("Socket 已经连接")
                    val outputStream = mysocket.getOutputStream()
                    message1++
                    val message = "Hello Server  $message1"

                    outputStream.write(message.toByteArray())
                    outputStream.flush()
                    //接收消息
                    // Receiving message from the server
                    val inputStream = mysocket.getInputStream()
                    val bufferedReader = BufferedReader(InputStreamReader(inputStream))
                    val response = bufferedReader.readLine() // Reads a line of text from the server
                    if (response != null) {
                        println("Message received from server: $response")
                        runOnUiThread {
                            val messageEditText: EditText = findViewById(R.id.editTextTextMultiLine)
                            println("messageEditText: ${messageEditText.text}")
                            messageEditText.append("\n$response")
                            messageEditText.isFocusable = false
                            messageEditText.isFocusableInTouchMode = false
                            messageEditText.isClickable = false
                        }
                    } else {
                        println("No response from server.")
                    }

                } else {
                    println("Socket 失败连接")
                }



            } catch (e: Exception) {
                e.printStackTrace()
                println("Socket 关闭")
                closeSocket()

            }
        }.start()
    }
    fun getSocket(): Socket? {
        return if (socket != null && !socket!!.isClosed) {
            socket
        } else {
            socket = Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT)
            socket
        }
    }

    fun closeSocket() {
        socket?.close()
        socket = null
    }

    override fun onDestroy() {
        super.onDestroy()
        handler!!.removeCallbacks(socketTask!!)
    }
}
代码解析
  1. 初始化 UI 和导航组件
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // 新增代码:
    handler = Handler(Looper.getMainLooper())
    socketTask = object : Runnable {
        override fun run() {
            sendSocketData()
            handler.postDelayed(this, INTERVAL_MS)
        }
    }
    handler.post(socketTask);

    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    setSupportActionBar(binding.toolbar)

    val navController = findNavController(R.id.nav_host_fragment_content_main)
    appBarConfiguration = AppBarConfiguration(navController.graph)
    setupActionBarWithNavController(navController, appBarConfiguration)

    binding.fab.setOnClickListener { view ->
        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
            .setAction("Action", null)
            .setAnchorView(R.id.fab).show()
    }
}
  1. 发送数据到服务器
private fun sendSocketData() {
    Thread {
        try {
            val mysocket = getSocket()
            if (mysocket != null) {
                println("Socket 已经连接")
                val outputStream = mysocket.getOutputStream()
                message1++
                val message = "Hello Server  $message1"

                outputStream.write(message.toByteArray())
                outputStream.flush()

                // 接收消息
                val inputStream = mysocket.getInputStream()
                val bufferedReader = BufferedReader(InputStreamReader(inputStream))
                val response = bufferedReader.readLine() // 从服务器读取一行文本
                if (response != null) {
                    println("Message received from server: $response")
                    runOnUiThread {
                        val messageEditText: EditText = findViewById(R.id.editTextTextMultiLine)
                        println("messageEditText: ${messageEditText.text}")
                        messageEditText.append("\n$response")
                        messageEditText.isFocusable = false
                        messageEditText.isFocusableInTouchMode = false
                        messageEditText.isClickable = false
                    }
                } else {
                    println("No response from server.")
                }
            } else {
                println("Socket 失败连接")
            }
        } catch (e: Exception) {
            e.printStackTrace()
            println("Socket 关闭")
            closeSocket()
        }
    }.start()
}
  1. 获取和关闭 Socket 连接
fun getSocket(): Socket? {
    return if (socket != null && !socket!!.isClosed) {
        socket
    } else {
        socket = Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT)
        socket
    }
}

fun closeSocket() {
    socket?.close()
    socket = null
}
  1. 生命周期管理
override fun onDestroy() {
    super.onDestroy()
    handler!!.removeCallbacks(socketTask!!)
}
总结

这段代码实现了以下几个关键功能:

在主线程中通过 Handler 定时发送数据到服务器。
在子线程中发送数据并通过 runOnUiThread 更新 UI。
管理 Socket 连接的打开和关闭。
在应用销毁时移除定时任务。
这样可以确保应用能够在后台持续与服务器通信,并在适当的时候更新 UI。

  • 这里的runOnUiThread很关键,如果没加这个,UI更新会报错。mask:1package com.example.android_kotlin_socke
  • fun getSocket()函数在这里实现了获取 Socket 连接的功能。如果 Socket 连接已建立,则返回该连接;否则,尝试创建新的 Socket 连接并返回。
    -closeSocket 函数在这里实现了关闭 Socket 连接的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值