Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1K
Vistas
¿Cómo trabajar con sockets UDP en iOS, rápido?

Estoy intentando conectarme al servidor UDP esp8266 local. SwiftSocket no tiene documentación. CocoaAsyncSocket no funciona. ¿Cómo conectar y enviar datos al servidor UDP? ¿Qué debería hacer?

Escribí un servidor python UDP de muestra e intenté conectarme a ellos a través de SwiftSocket y CocoaAsyncSocket. No recibo comentarios de la aplicación. El servidor no recibe conexiones. Por ejemplo, uno de los intentos más:

 var connection = NWConnection(host: "255.255.255.255", port: 9093, using: .udp) connection.stateUpdateHandler = { (newState) in switch (newState) { case .ready: print("ready") case .setup: print("setup") case .cancelled: print("cancelled") case .preparing: print("Preparing") default: print("waiting or failed") break } } connection.start(queue: .global()) connection.send(content: "Xyu".data(using: String.Encoding.utf8), completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in print(NWError) }))) connection.receiveMessage { (data, context, isComplete, error) in print("Got it") print(data) }

No puedo conectarme al servidor

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

¡Esta solución funciona para mí! Gracias @ Paulw11
Swift 4, XCode 10.1, iOS 12.0
Simplemente conéctese al servidor UDP público (Esta NO es la versión óptima pero funciona):

 import UIKit import Network class ViewController: UIViewController { var connection: NWConnection? var hostUDP: NWEndpoint.Host = "iperf.volia.net" var portUDP: NWEndpoint.Port = 5201 override func viewDidLoad() { super.viewDidLoad() // Hack to wait until everything is set up var x = 0 while(x<1000000000) { x+=1 } connectToUDP(hostUDP,portUDP) } func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) { // Transmited message: let messageToUDP = "Test message" self.connection = NWConnection(host: hostUDP, port: portUDP, using: .udp) self.connection?.stateUpdateHandler = { (newState) in print("This is stateUpdateHandler:") switch (newState) { case .ready: print("State: Ready\n") self.sendUDP(messageToUDP) self.receiveUDP() case .setup: print("State: Setup\n") case .cancelled: print("State: Cancelled\n") case .preparing: print("State: Preparing\n") default: print("ERROR! State not defined!\n") } } self.connection?.start(queue: .global()) } func sendUDP(_ content: Data) { self.connection?.send(content: content, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in if (NWError == nil) { print("Data was sent to UDP") } else { print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)") } }))) } func sendUDP(_ content: String) { let contentToSendUDP = content.data(using: String.Encoding.utf8) self.connection?.send(content: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in if (NWError == nil) { print("Data was sent to UDP") } else { print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)") } }))) } func receiveUDP() { self.connection?.receiveMessage { (data, context, isComplete, error) in if (isComplete) { print("Receive is complete") if (data != nil) { let backToString = String(decoding: data!, as: UTF8.self) print("Received message: \(backToString)") } else { print("Data == nil") } } } } }
over 4 years ago · Santiago Trujillo Denunciar

0

Debe esperar hasta que su conexión esté ready antes de intentar enviar o recibir datos. También deberá mantener una referencia sólida a su conexión en una propiedad para evitar que se libere tan pronto como finalice la función.

 var connection: NWConnection? func someFunc() { self.connection = NWConnection(host: "255.255.255.255", port: 9093, using: .udp) self.connection?.stateUpdateHandler = { (newState) in switch (newState) { case .ready: print("ready") self.send() self.receive() case .setup: print("setup") case .cancelled: print("cancelled") case .preparing: print("Preparing") default: print("waiting or failed") } } self.connection?.start(queue: .global()) } func send() { self.connection?.send(content: "Test message".data(using: String.Encoding.utf8), completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in print(NWError) }))) } func receive() { self.connection?.receiveMessage { (data, context, isComplete, error) in print("Got it") print(data) } }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda