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>