Search code examples
swiftserversocketcfnetwork

Socket Server via CFNetwork in Swift 4


I am new in Swift.
I am studying to write a pure swift app to be socket server.
code is as below

server = CFSocketCreate(kCFAllocatorDefault, AF_INET, 
    SOCK_STREAM, IPPROTO_TCP, callbackOpts.rawValue, {
       (socket, type, address, data, info) in
       print("type ->\(type)")
    }, nil)

let size = MemoryLayout<sockaddr_in>.size
addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
addr.sin_family = sa_family_t(AF_INET); /* Address family */
addr.sin_port = in_port_t(10001); /* Or a specific port */
addr.sin_addr.s_addr = in_addr_t(INADDR_ANY);

let addrInPtr = withUnsafeMutablePointer(to: &addr) { ptr in
    return ptr.withMemoryRebound(to: UInt8.self, capacity: size){
        return $0
    }
}
let sincfd = CFDataCreate(
    kCFAllocatorDefault,
    addrInPtr,
    size)

let result = CFSocketSetAddress(server, sincfd) 
switch result {
case .success:
    print("xx sucess")
case .timeout:
    print("xx timeout")
case .error:
    print("xx error")
}

let runLoopSourceRef = CFSocketCreateRunLoopSource(
                           kCFAllocatorDefault, server, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), 
                   runLoopSourceRef, CFRunLoopMode.defaultMode)

I got "xx success" when binder.
I can not connect this server from client.
Does someone give me a hint what problem is and how to do a server?

I know there are some 3rd party library can do that, but I am studying Swift and try to understand how to use CFNetwork.


Solution

  • I just found my problem.
    It was caused by the byte order of port number.
    Code should be

    addr.sin_port = in_port_t(CFSwapInt16HostToBig(10001))