UDP fast connection

I am new to Swift and have some questions about UDP connections.

Can someone provide a link or short lines of code showing how I can connect a Swift client to a Java server?

+3
source share
2 answers

You can simply use the appropriate C functions from the Darwin module. The part that is a bit complicated is casting from sockaddr_xyz structs to a generic sockaddr (maybe someone has a better solution than mine ...). Otherwise, it is pretty straight forward.

Updated for Swift 0.2 aka Xcode 6.3.1 (strlen () must be converted to Int).

Example:

let textToSend = "Hello World!"

func htons(value: CUnsignedShort) -> CUnsignedShort {
  return (value << 8) + (value >> 8);
}

let INADDR_ANY = in_addr(s_addr: 0)

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(1337),
  sin_addr:   INADDR_ANY,
  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, Int(strlen(cstr)), 0,
           addrptr, socklen_t(addr.sin_len))
  }
}
+3
source

, GCD AsyncSocket, iOS, - Swift.

, Async, SwiftSocket.

github (https://github.com/xyyc/SwiftSocket) , .

, Async objective-c. , : D

+1

All Articles