连接的创建可以放在viewmodel中。
1.创建连接
var isConnected:MutableState<Boolean> = mutableStateOf(false)
val client = mutableStateOf<Socket?>(null)
var ip="192.168.100.102"
var port = "61001"
init {
reConnectNet()
}
fun reConnectNet()
{
if (isConnected.value) {
disconnect(client, isConnected)
} else {
connect(ip, port, client, isConnected)
}
}
fun connect(
ip: String,
port: String,
client: MutableState<Socket?>,
isConnected: MutableState<Boolean>
) {
if (ip.isEmpty() || port.isEmpty()) {
// IP地址或端口号为空,进行错误处理
return
}
GlobalScope.launch(Dispatchers.IO) {
try {
val socket = Socket(ip, port.toInt())
client.value = socket
isConnected.value = true
socket.outputStream.write("Hello from the client!".toByteArray())
} catch (e: IOException) {
e.printStackTrace()
// 处理连接异常
Log.d("scoreInfo",e.toString())
}
}
}
2.断开连接
fun disconnect(client: MutableState<Socket?>, isConnected: MutableState<Boolean>) {
client.value?.let { socket ->
if (!socket.isClosed) {
socket.close()
}
isConnected.value = false
client.value = null
}
}
3.数据发送
fun sendData(input:ByteArray)
{
if (!isConnected.value) {
// 如果未连接,进行错误处理或其他操作
return
}
GlobalScope.launch(Dispatchers.IO) {
try {
client?.let { socket ->
val outputStream = socket.value?.getOutputStream()
outputStream?.write(
input
)
outputStream?.flush()
// 不关闭outputStream,保持连接
}
} catch (e: IOException) {
e.printStackTrace()
// 处理发送数据异常
}
}
}
fun sendData(input:String)
{
val byteArray = input.toByteArray()
sendData(byteArray)
}