user3838885
user3838885

Reputation: 41

Swift UDP Connection

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

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

Upvotes: 4

Views: 12800

Answers (2)

hnh
hnh

Reputation: 14795

You can just use the relevant C functions, from the 'Darwin' module. The part which is a bit tricky is the casting from sockaddr_xyz structs to the 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).

Sample:

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))
  }
}

Upvotes: 3

Ash
Ash

Reputation: 45

After pretty extensive research coming up with only basic pointers towards GCD's AsyncSocket, and being a pure Swift trained iOS programmer, I looked for something with native Swift socket support.

Thankfully, I found a much simpler alternative to using Async, called SwiftSocket.

The github (https://github.com/xyyc/SwiftSocket) has examples for most sockets, and is ready to use by copying just a few files into a project.

For swift-only devs, I feel its underutilized and will quickly replace Async for non-objective-c apps. Then again I'm pretty new to this stuff so I may be way off :D

Upvotes: 1

Related Questions