Servidor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.io.BufferedReader import java.io.InputStreamReader import java.io.PrintWriter import java.net.ServerSocket class TCPServer { fun startServer() { try { val serverSocket = ServerSocket(6000) println("Servidor TCP iniciado. Esperando conexiones...") while (true) { val clientSocket = serverSocket.accept() println("Cliente conectado desde: ${clientSocket.inetAddress.hostAddress}") val reader = BufferedReader(InputStreamReader(clientSocket.inputStream)) var message: String? do { message = reader.readLine() if (message != null) { println("Mensaje recibido del cliente: $message") } } while (message != null && message != "fin") reader.close() clientSocket.close() } } catch (e: Exception) { e.printStackTrace() } } } fun main() { val server = TCPServer() server.startServer() } |
Cliente
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import SwiftUI import Foundation @main struct cliente: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { let serverAddress = "192.168.1.55" let serverPort = 6000 let messageToSend = "Hello" 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") } // Cerrar las conexiones después de enviar el mensaje inputStreamUnwrapped.close() outputStreamUnwrapped.close() } } |