Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement UDP client and send data in Swift on iPhone?

I want to develop UDP client and send data in Swift.

I have reference the following link:

Swift: Receive UDP with GCDAsyncUdpSocket

Retrieving a string from a UDP server message

Swift UDP Connection

But I could not find a good way to implement UDP in Swift.

Can someone teach me How to implement UDP client and send data in Swift on iPhone?

like image 942
Martin Avatar asked Feb 03 '15 09:02

Martin


2 Answers

for me, I used this, and its usage:

broadcastConnection = UDPBroadcastConnection(port: 35602) { [unowned self] (response: (ipAddress: String, port: Int, response: [UInt8])) -> Void in
    print("Received from \(response.ipAddress):\(response.port):\n\n\(response.response)")
}
like image 50
AbdulMomen عبدالمؤمن Avatar answered Sep 25 '22 14:09

AbdulMomen عبدالمؤمن


This looks like a dupe to Swift UDP Connection.

Refactoring the example a little bit:

let INADDR_ANY = in_addr(s_addr: 0)

udpSend("Hello World!", address: INADDR_ANY, port: 1337)

func udpSend(textToSend: String, address: in_addr, port: CUnsignedShort) {
  func htons(value: CUnsignedShort) -> CUnsignedShort {
    return (value << 8) + (value >> 8);
  }

  let fd = socket(AF_INET, SOCK_DGRAM, 0) // DGRAM makes it UDP

  var addr = sockaddr_in(
    sin_len:    __uint8_t(sizeof(sockaddr_in)),
    sin_family: sa_family_t(AF_INET),
    sin_port:   htons(port),
    sin_addr:   address,
    sin_zero:   ( 0, 0, 0, 0, 0, 0, 0, 0 )
  )

  textToSend.withCString { cstr -> Void in
    withUnsafePointer(&addr) { ptr -> Void in
      let addrptr = UnsafePointer<sockaddr>(ptr)
      sendto(fd, cstr, strlen(cstr), 0, addrptr, socklen_t(addr.sin_len))
    }
  }

  close(fd)
}

If you have the target IP as a string, use inet_pton() to convert it to an in_addr. Like so:

var addr = in_addr()
inet_pton(AF_INET, "192.168.0.1", &buf)

Feel free to steal code from over here: SwiftSockets

Oh, and if you plan to do any serious network programming, grab this book: Unix Network Programming

like image 30
hnh Avatar answered Sep 25 '22 14:09

hnh