Servidor en Android Studio
AndroidManifest.xml
<?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" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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:label="@string/app_name"
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>
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.ServerSocket
class MainActivity : ComponentActivity() {
private val port = 3333 // Puerto para la conexión
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
startServer()
}
}
private fun startServer() {
GlobalScope.launch(Dispatchers.IO) {
try {
val serverSocket = ServerSocket(port)
while (true) {
val client = serverSocket.accept()
val inputStream = client.getInputStream()
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
val message = bufferedReader.readLine()
showMessage(message)
bufferedReader.close()
client.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun showMessage(message: String?) {
runOnUiThread {
Toast.makeText(this, "Mensaje recibido: $message", Toast.LENGTH_SHORT).show()
}
}
}
Cliente con Swift desde Xcode
helloApp.swift
import SwiftUI
@main
struct helloApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
ContentView.swift
import SwiftUI
import Foundation
struct ContentView: View {
let serverAddress = "192.168.0.18"
let serverPort = 3333
let messageToSend = "Hello, TCP!"
var body: some View {
VStack {
Button("Enviar Mensaje") {
sendMessage()
}
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(8)
}
.padding()
}
func sendMessage() {
var inputStream: InputStream?
var outputStream: OutputStream?
Stream.getStreamsToHost(withName: serverAddress, port: serverPort, inputStream: &inputStream, outputStream: &outputStream)
guard let inputStreamUnwrapped = inputStream, let outputStreamUnwrapped = outputStream else {
print("Error al establecer la conexión")
return
}
inputStreamUnwrapped.open()
outputStreamUnwrapped.open()
let data = messageToSend.data(using: .utf8)!
let bytesWritten = outputStreamUnwrapped.write((data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), maxLength: data.count)
if bytesWritten > 0 {
print("Mensaje enviado con éxito")
} else {
print("Error al enviar el mensaje")
}
inputStreamUnwrapped.close()
outputStreamUnwrapped.close()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Publicado el día 8 de diciembre de 2023 CATEGORÍAS Android , Kotlin , Lo mejor , Swift