简体   繁体   English

Swift 4中通过CFNetwork的套接字服务器

[英]Socket Server via CFNetwork in Swift 4

I am new in Swift. 我是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. 活页夹时我获得了“ xx成功”。
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. 我知道有一些第三方库可以做到这一点,但是我正在研究Swift,并试图了解如何使用CFNetwork。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM