kotlin,socket网络传输数据

MainActivity.kt

Kotlin 复制代码
package com.example.applicationtest2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
//import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button
import android.widget.TextView
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.net.Socket


class MainActivity : AppCompatActivity() {
    private lateinit var transferButton: Button
    private lateinit var resultTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        transferButton = findViewById(R.id.transferButton)
        resultTextView = findViewById(R.id.resultTextView)

        transferButton.setOnClickListener {
            Thread {
                val serverAddress = "127.0.0.1" // Kotlin 服务器的 IP 地址
                val serverPort = 12345 // Kotlin 服务器的端口号
                val filePath = "/path/to/file" // 待传输的文件路径

                try {
                    val socket = Socket(serverAddress, serverPort)
                    val file = File(filePath)

                    val outputStream = BufferedOutputStream(socket.getOutputStream())
                    val inputStream = BufferedInputStream(FileInputStream(file))

                    // 发送文件名和文件大小给 Kotlin 服务器
                    val fileNameBytes = file.name.toByteArray()
                    val fileSizeBytes = file.length().toString().toByteArray()
                    outputStream.write(fileNameBytes.size)
                    outputStream.write(fileNameBytes)
                    outputStream.write(fileSizeBytes.size)
                    outputStream.write(fileSizeBytes)
                    outputStream.flush()

                    // 接收服务器确认
                    val confirmation = socket.getInputStream().read()
                    if (confirmation == 1) {
                        // 开始传输文件数据
                        val buffer = ByteArray(8192)
                        var bytesRead: Int
                        while (inputStream.read(buffer).also { bytesRead = it } != -1) { //从输入流读取数据到缓冲区中
                            outputStream.write(buffer, 0, bytesRead)  //将缓冲区的数据写入到输出流中
                            outputStream.flush()

                            // 等待对方确认
                            val acknowledgement = socket.getInputStream().read()
                            if (acknowledgement != 1) {
                                runOnUiThread {
                                    resultTextView.text = "传输失败,未收到对方确认"
                                }
                                break
                            }
                        }

                        socket.shutdownOutput()

                        // 接收并显示传输结果
                        val result = socket.getInputStream().bufferedReader().readLine()
                        runOnUiThread {
                            resultTextView.text = result
                        }
                    } else {
                        runOnUiThread {
                            resultTextView.text = "传输失败,对方拒绝接收"
                        }
                    }

                    inputStream.close()
                    outputStream.close()
                    socket.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                    runOnUiThread {
                        resultTextView.text = "传输失败:" + e.message
                    }
                }
            }.start()
        }
    }
}

activity_mian.xml

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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/transferButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="传输" />

    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="" />


</LinearLayout>
相关推荐
androidwork6 分钟前
使用 Kotlin 和 Jetpack Compose 开发 Wear OS 应用的完整指南
android·kotlin
_龙小鱼_9 分钟前
Kotlin变量与数据类型详解
开发语言·微信·kotlin
繁依Fanyi1 小时前
Animaster:一次由 CodeBuddy 主导的 CSS 动画编辑器诞生记
android·前端·css·编辑器·codebuddy首席试玩官
奔跑吧 android3 小时前
【android bluetooth 框架分析 02】【Module详解 6】【StorageModule 模块介绍】
android·bluetooth·bt·aosp13·storagemodule
网络空间小黑6 小时前
TCP/IP 知识体系
网络·网络协议·tcp/ip·计算机网络·5g·wireshark·信息与通信
Dotrust东信创智7 小时前
面向SDV的在环测试深度解析——仿真中间件SIL KIT应用篇
网络·中间件·汽车
田一一一7 小时前
Android framework 中间件开发(三)
android·中间件·framework·jni
leoufung8 小时前
ECPF 简介
linux·网络·kernel
救救孩子把10 小时前
MCP本地高效与云端实时:stdio 与 HTTP+SSE 传输机制深度对比
网络·网络协议·http·sse·mcp·stdio
hao_wujing10 小时前
衡量 5G 和未来网络的安全性
网络·5g